/**
 * admin-ajax.php transport, through @wordpress/api-fetch. The screen reuses
 * the plugin's existing AJAX actions (API key, connection test, chat history,
 * feature requests), so everything goes through one helper.
 */
import apiFetch from '@wordpress/api-fetch';
import boot from './boot';
import type { AjaxResponse } from '@/types';

type Fields = Record<string, string | number | boolean | null | undefined>;

/**
 * @param action wp_ajax_ action name.
 * @param data   Flat map of request fields.
 * @param method 'POST' or 'GET'.
 * @return Parsed JSON reply. Rejects on network errors and non-2xx replies.
 */
export function ajax<T = unknown>( action: string, data: Fields = {}, method: 'GET' | 'POST' = 'POST' ): Promise<AjaxResponse<T>> {
    const params = new URLSearchParams( { action } );
    Object.entries( data ).forEach( ( [ key, value ] ) => params.append( key, String( value ?? '' ) ) );

    if ( 'GET' === method ) {
        return apiFetch( { url: `${ boot.ajaxUrl }?${ params }`, method } );
    }

    return apiFetch( { url: boot.ajaxUrl, method, body: params } );
}

/**
 * The message from a wp_send_json_error() reply, whether the handler sent a
 * string or an array with a message key.
 */
export function errorMessage( response: AjaxResponse | null | undefined, fallback: string ): string {
    const data = response?.data;
    if ( 'string' === typeof data && data ) {
        return data;
    }
    if ( data && 'object' === typeof data && 'message' in data && 'string' === typeof data.message && data.message ) {
        return data.message;
    }
    return fallback;
}
