/**
 * AJAX calls to admin-ajax.php.
 *
 * A fresh nonce is requested right before every submit, so the form keeps working on sites
 * that serve cached HTML (the nonce printed into a cached page expires after 12–24 hours).
 */

type AjaxResponse<T> = { success: boolean; data: T };

async function post<T>(fields: Record<string, string>): Promise<AjaxResponse<T>> {
    const body = new FormData();
    Object.entries(fields).forEach(([key, value]) => body.append(key, value));

    const response = await fetch(accessible_docs_object.ajax_url, { method: 'POST', body, credentials: 'same-origin' });
    if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
    }
    return response.json();
}

/** Sends the request and resolves with the document status: 'in-process' | 'completed'. */
export async function requestAccessibleDocument(email: string, pdfUrl: string): Promise<string> {
    const nonceResponse = await post<{ nonce: string }>({ action: 'accessible_docs_nonce' });
    if (!nonceResponse.success || !nonceResponse.data?.nonce) {
        throw new Error('Could not get a security token.');
    }

    const result = await post<{ status?: string; error?: string }>({
        action: 'accessible_docs_request',
        nonce: nonceResponse.data.nonce,
        email,
        url: pdfUrl,
    });

    if (!result.success || !result.data?.status || result.data.status === 'error') {
        throw new Error(result.data?.error || 'Request failed.');
    }
    return result.data.status;
}
