/**
 * API client for Formipay admin interface
 * Handles nonce-secured requests to WordPress admin-ajax.php
 */

export const API_BASE = window.formipayAdmin?.ajaxUrl || '/wp-admin/admin-ajax.php';
export const NONCE = window.formipayAdmin?.nonce || '';
export const REST_BASE = window.formipayAdmin?.restUrl || '/wp-json/formipay/v1';

/**
 * Generic AJAX request handler with nonce
 */
export async function ajaxRequest(action, data = {}) {
    const formData = new FormData();

    formData.append('action', action);
    formData.append('_wpnonce', NONCE);

    Object.keys(data).forEach(key => {
        if (typeof data[key] === 'object') {
            formData.append(key, JSON.stringify(data[key]));
        } else {
            formData.append(key, data[key]);
        }
    });

    try {
        const response = await fetch(API_BASE, {
            method: 'POST',
            credentials: 'same-origin',
            body: formData,
        });

        const result = await response.json();

        if (!response.ok || result.success === false) {
            throw new Error(result.message || 'Request failed');
        }

        return result;
    } catch (error) {
        console.error(`AJAX error [${action}]:`, error);
        throw error;
    }
}

/**
 * REST API request handler
 */
export async function apiRequest(endpoint, options = {}) {
    const url = `${REST_BASE}${endpoint}`;

    const defaultOptions = {
        headers: {
            'Content-Type': 'application/json',
            'X-WP-Nonce': NONCE,
        },
    };

    try {
        const response = await fetch(url, { ...defaultOptions, ...options });
        const result = await response.json();

        if (!response.ok) {
            throw new Error(result.message || 'API request failed');
        }

        return result;
    } catch (error) {
        console.error(`API error [${endpoint}]:`, error);
        throw error;
    }
}

/**
 * Orders API
 */
export const ordersApi = {
    list: (params = {}) => ajaxRequest('formipay_tabledata_orders', params),
    get: (orderId) => ajaxRequest('formipay_get_order', { order_id: orderId }),
    updateStatus: (orderId, status) => ajaxRequest('formipay_update_order_status', {
        order_id: orderId,
        status,
    }),
    delete: (orderIds) => ajaxRequest('formipay_bulk_delete_order', { ids: orderIds }),
};

/**
 * Customers API
 */
export const customersApi = {
    list: (params = {}) => ajaxRequest('formipay_tabledata_customers', params),
    get: (customerId) => ajaxRequest('formipay_get_customer', { customer_id: customerId }),
};

/**
 * Products API
 */
export const productsApi = {
    list: (params = {}) => ajaxRequest('formipay_tabledata_products', params),
    get: (productId) => ajaxRequest('formipay_get_product', { post_id: productId }),
    getVariables: (productId) => ajaxRequest('get_product_variables', { post_id: productId }),
};

/**
 * Forms API
 */
export const formsApi = {
    list: (params = {}) => ajaxRequest('formipay_tabledata_forms', params),
    get: (formId) => ajaxRequest('formipay_get_form', { post_id: formId }),
};

/**
 * Coupons API
 */
export const couponsApi = {
    list: (params = {}) => ajaxRequest('formipay_tabledata_coupons', params),
    check: (code, formId) => ajaxRequest('formipay_check_coupon', { code, form_id: formId }),
};

/**
 * License API
 */
export const licenseApi = {
    verify: (key) => ajaxRequest('formipay_verify_license', { license_key: key }),
    activate: (key) => ajaxRequest('formipay_activate_license', { license_key: key }),
    deactivate: (key) => ajaxRequest('formipay_deactivate_license', { license_key: key }),
};
