/**
 * API utility functions for Echo Rewards React app
 * 
 * This file contains helper functions for making AJAX requests
 * to WordPress backend following WordPress coding standards.
 */

// Get config from global variables
let config = {};
if (window.ecreAdmin) {
    config = Object.assign({}, window.ecreAdmin);
} else if (window.ecreFrontend) {
    config = Object.assign({}, window.ecreFrontend);
} else {
    // Fallback configuration
    console.warn('WordPress globals not found, using fallback configuration');
    config = {
        ajaxurl: window.ajaxurl || '/wp-admin/admin-ajax.php',
        nonce: '' // This will cause a warning but won't break the request
    };
}

/**
 * Make an AJAX request to WordPress backend
 * 
 * @param {string} action - The WordPress AJAX action name
 * @param {Object} data - Additional data to send with the request
 * @param {Object} options - Request options (method, headers, etc.)
 * @returns {Promise} - Promise that resolves with the response data
 */
export const makeAjaxRequest = async (action, data = {}, options = {}) => {
    // Check if we have the required WordPress globals
    if (!config.ajaxurl && !window.ajaxurl) {
        throw new Error('WordPress AJAX URL not found. Make sure wp_localize_script is properly configured.');
    }
    
    if (!config.nonce) {
        console.warn('WordPress nonce not found. This may cause security issues.');
    }

    const defaultOptions = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
    };

    const requestOptions = { ...defaultOptions, ...options };

    // Prepare form data
    const formData = new URLSearchParams();
    formData.append('action', action);
    formData.append('nonce', config.nonce || '');

    // Add additional data
    Object.keys(data).forEach(key => {
        if (data[key] !== null && data[key] !== undefined) {
            formData.append(key, data[key]);
        }
    });

    // Use config.ajaxurl first, then fallback to window.ajaxurl, then default
    const ajaxUrl = config.ajaxurl || window.ajaxurl || '/wp-admin/admin-ajax.php';

    try {
        const response = await fetch(ajaxUrl, {
            ...requestOptions,
            body: formData,
        });

        if (!response.ok) {
            const errorText = await response.text();
            console.error('HTTP Error Response:', errorText);
            throw new Error(`HTTP error! status: ${response.status} - ${errorText.substring(0, 200)}`);
        }

        const responseText = await response.text();
    
        let result;
        try {
            result = JSON.parse(responseText);
        } catch (parseError) {
            console.error('JSON Parse Error:', parseError);
            console.error('Response text:', responseText);
            throw new Error(`Invalid JSON response: ${responseText.substring(0, 200)}`);
        }

        if (!result.success) {
            const errorMessage = result.data?.message || result.data || 'Request failed';
            console.error('AJAX Error:', errorMessage);
            throw new Error(errorMessage);
        }

        return result.data;
    } catch (error) {
        console.error('AJAX request failed:', error);
        throw error;
    }
};

/**
 * Get all referrers data with pagination and filtering
 * 
 * @param {Object} params - Request parameters
 * @param {number} params.limit - Number of records to fetch (default: 50)
 * @param {number} params.offset - Offset for pagination (default: 0)
 * @param {string} params.search - Search term (default: '')
 * @param {string} params.time_filter - Time filter (default: 'all')
 * @param {Object} params.filters - Additional filters (default: {})
 * @returns {Promise} - Promise that resolves with referrers data
 */
export const getAllReferrers = async (params = {}) => {
    const {
        limit = 50,
        offset = 0,
        search = '',
        time_filter = 'all',
        filters = {}
    } = params;

    return makeAjaxRequest('ecre_get_all_referrers', {
        limit,
        offset,
        search,
        time_filter,
        filters: JSON.stringify(filters)
    });
};

/**
 * Get detailed information for a specific referrer
 * 
 * @param {number} referrerId - The ID of the referrer
 * @returns {Promise} - Promise that resolves with referrer details
 */
export const getReferrerDetails = async (referrerId) => {
    if (!referrerId || referrerId <= 0) {
        throw new Error('Invalid referrer ID');
    }

    return makeAjaxRequest('ecre_get_referrer_details', {
        referrer_id: referrerId
    });
};

/**
 * Get dashboard summary data
 * 
 * @returns {Promise} - Promise that resolves with dashboard summary
 */
export const getDashboardSummary = async () => {
    return makeAjaxRequest('ecre_get_dashboard_summary');
};

/**
 * Convert time filter from React format to PHP format
 * 
 * @param {string} reactTimeFilter - Time filter from React component
 * @returns {string} - PHP-compatible time filter
 */
export const convertTimeFilter = (reactTimeFilter) => {
    const filterMap = {
        'All Time': 'all',
        '1 Month': '1_month',
        '3 Month': '3_month',
        '5 Month': '6_month', // Mapping 5 Month to 6 Month for consistency
        '1 Year': '1_year'
    };

    return filterMap[reactTimeFilter] || 'all';
};

/**
 * Handle API errors consistently
 * 
 * @param {Error} error - The error object
 * @param {string} context - Context where the error occurred
 * @returns {Object} - Formatted error object
 */
export const handleApiError = (error, context = 'API request') => {
    console.error(`${context} failed:`, error);
    
    return {
        success: false,
        error: error.message || 'An unexpected error occurred',
        context
    };
};

/**
 * Debounce function for search inputs
 * 
 * @param {Function} func - Function to debounce
 * @param {number} wait - Wait time in milliseconds
 * @returns {Function} - Debounced function
 */
export const debounce = (func, wait) => {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
};