import { API_BASE_URL, API_FUNCTION_KEY } from '../auth/authConfig';

/**
 * Registration API Service
 *
 * Calls the Registration Azure Function endpoints.
 * Matches the contract in RegistrationFunctions.cs:
 *
 *   POST /api/registration/register             ← requires Bearer token (CIAM JWT)
 *   GET  /api/registration/pending              ← admin; Function key only
 *   GET  /api/registration/item/{id}            ← admin; Function key only
 *   POST /api/registration/action/{id}/complete ← admin; Function key only
 *   POST /api/registration/action/{id}/reject   ← admin; Function key only
 *
 * Note: entraSubjectId is NOT sent by the client — the server extracts it
 * from the validated JWT token so it cannot be spoofed.
 */

const USE_MOCK = !API_BASE_URL;

// ─── Helpers ──────────────────────────────────────────────────────────────

async function apiFetch(path, method = 'GET', body = null, token = null) {
    const url = `${API_BASE_URL}${path}`;
    const headers = { 'Content-Type': 'application/json' };

    // Bearer token — used on the Register endpoint so the Function can
    // validate the caller's identity via the CIAM JWT.
    if (token) {
        headers['Authorization'] = `Bearer ${token}`;
    }

    // Function key — used on admin endpoints called by Management API.
    // Not required for the public Register endpoint.
    if (API_FUNCTION_KEY) {
        headers['x-functions-key'] = API_FUNCTION_KEY;
    }

    const opts = { method, headers };
    if (body) opts.body = JSON.stringify(body);

    try {
        const res = await fetch(url, opts);
        if (!res.ok) {
            const text = await res.text();
            console.error(`[API] ${method} ${path} → ${res.status}:`, text.substring(0, 200));
            return { ok: false, error: `HTTP ${res.status}: ${text.substring(0, 100)}` };
        }
        return await res.json();
    } catch (err) {
        console.error(`[API] Network error on ${path}:`, err.message);
        return { ok: false, error: 'Network error: ' + err.message };
    }
}


// ─── Mock Implementation ───────────────────────────────────────────────────

const mockDelay = (ms = 500) => new Promise(r => setTimeout(r, ms));

const MockApi = {
    async register(request) {
        await mockDelay(800);
        console.log('[Mock] register:', request);
        return {
            ok: true,
            registrationId: 'reg-' + crypto.randomUUID().slice(0, 8),
        };
    },
};


// ─── Public API ────────────────────────────────────────────────────────────

/**
 * Submit a new registration.
 * Maps to POST /api/registration/register
 *
 * @param {object} data — matches RegisterRequest model (without entraSubjectId —
 *   the server extracts that from the validated Bearer token)
 * @param {string} token — CIAM ID token from MSAL (required in production)
 *
 * @returns {{ ok, registrationId?, error? }}
 */
export async function submitRegistration(data, token) {
    if (USE_MOCK) return MockApi.register(data);
    return apiFetch('/api/registration/register', 'POST', data, token);
}

/**
 * Check registration status by ID (for returning users / admin use).
 * Maps to GET /api/registration/item/{id}
 */
export async function getRegistrationStatus(registrationId) {
    if (USE_MOCK) {
        await mockDelay(300);
        return { ok: true, applicant: null };
    }
    return apiFetch(`/api/registration/item/${registrationId}`);
}
