/**
 * Aysa API Service - Database-Based Authentication
 * Updated to work without cookies, using WordPress database authentication
 */

const aysaApiNativeConsole = window.console || {
    log: function() {},
    warn: function() {},
    error: function() {}
};
var console = {
    log: function() {
        if (window.AYSA_DEBUG === true) {
            aysaApiNativeConsole.log.apply(aysaApiNativeConsole, arguments);
        }
    },
    warn: function() {
        if (window.AYSA_DEBUG === true) {
            aysaApiNativeConsole.warn.apply(aysaApiNativeConsole, arguments);
        }
    },
    error: function() {
        aysaApiNativeConsole.error.apply(aysaApiNativeConsole, arguments);
    }
};

const AysaAPI = (function($) {
    'use strict';
    
    let apiEndpoints = {};
    let baseUrl = '';
    let aysa_user_id = null; // Aysa user ID (from external API)
    let wp_user_id = null; // WordPress user ID

    function resolveAjaxUrl() {
        return (typeof aysa_ajax !== 'undefined' && aysa_ajax.ajax_url)
            ? aysa_ajax.ajax_url
            : (typeof aysaParams !== 'undefined' && aysaParams.ajax_url)
                ? aysaParams.ajax_url
                : '/wp-admin/admin-ajax.php';
    }

    function resolveAuthNonce() {
        if (typeof aysa_ajax !== 'undefined' && aysa_ajax.nonce) {
            return aysa_ajax.nonce;
        }
        if (typeof aysaParams !== 'undefined') {
            if (aysaParams.ajax_nonce) {
                return aysaParams.ajax_nonce;
            }
            if (aysaParams.generic_nonce) {
                return aysaParams.generic_nonce;
            }
            if (aysaParams.nonce) {
                return aysaParams.nonce;
            }
        }
        return '';
    }

    function parseAjaxErrorMessage(xhr) {
        if (!xhr || typeof xhr !== 'object') {
            return '';
        }
        if (xhr.responseJSON) {
            if (typeof xhr.responseJSON.data === 'string') {
                return xhr.responseJSON.data;
            }
            if (xhr.responseJSON.data && typeof xhr.responseJSON.data.message === 'string') {
                return xhr.responseJSON.data.message;
            }
            if (typeof xhr.responseJSON.message === 'string') {
                return xhr.responseJSON.message;
            }
        }
        if (typeof xhr.responseText === 'string' && xhr.responseText.trim() !== '') {
            return xhr.responseText.trim();
        }
        return '';
    }
    
    /**
     * Initialize the API service
     */
    function init() {
        console.log('[AysaAPI] Initializing API service with database authentication...');
        
        // Load API configuration
        loadApiConfig();
        
        // Check authentication status on init (without cookies)
        checkAuthStatus().then(function(authStatus) {
            if (authStatus.authenticated) {
                aysa_user_id = authStatus.aysa_user_id;
                wp_user_id = authStatus.wp_user_id;
                console.log('[AysaAPI] User authenticated:', { wp_user_id: wp_user_id, aysa_user_id: aysa_user_id });
            } else {
                console.log('[AysaAPI] User not authenticated:', authStatus.source);
            }
        }).catch(function(error) {
            console.log('[AysaAPI] Auth check failed:', error);
        });
    }
    
    /**
     * Load API configuration from PHP
     */
    function loadApiConfig() {
        if (typeof aysaApiConfig !== 'undefined') {
            apiEndpoints = aysaApiConfig.endpoints || {};
            baseUrl = aysaApiConfig.baseUrl || '';
            console.log('[AysaAPI] Configuration loaded from global aysaApiConfig with', Object.keys(apiEndpoints).length, 'endpoints');
            console.log('[AysaAPI] Base URL:', baseUrl);
            return;
        }

        // Fallback: try to retrieve from localized objects
        let localizedConfig = null;
        if (typeof aysa_ajax !== 'undefined' && aysa_ajax.api_config) {
            localizedConfig = aysa_ajax.api_config;
        } else if (typeof aysaParams !== 'undefined' && aysaParams.api_config) {
            localizedConfig = aysaParams.api_config;
        }

        if (localizedConfig) {
            apiEndpoints = localizedConfig.endpoints || {};
            baseUrl = localizedConfig.baseUrl || localizedConfig.base_url || '';
            console.log('[AysaAPI] Configuration loaded from localized object with', Object.keys(apiEndpoints).length, 'endpoints');
            console.log('[AysaAPI] Base URL:', baseUrl);
        } else {
            console.warn('[AysaAPI] No API configuration found');
            // Production-safe fallback for live browser requests.
            baseUrl = 'https://api.aysa.ai/';
            console.log('[AysaAPI] Using fallback base URL:', baseUrl);
        }
    }
    
    /**
     * Get URL for a specific endpoint
     * @param {string} endpointName - The name of the endpoint
     * @param {object} urlParams - Parameters to replace in URL (e.g., {id: 123})
     * @param {object} queryParams - Query parameters to append
     * @returns {string|null} - The complete URL or null if endpoint not found
     */
    function getEndpointUrl(endpointName, urlParams = {}, queryParams = {}) {
        if (!apiEndpoints[endpointName]) {
            console.error('[AysaAPI] Endpoint not found:', endpointName);
            return null;
        }
        
        let url = apiEndpoints[endpointName];
        
        // Use production API base URL
        const selectedBaseUrl = baseUrl;
        
        // Ensure we include /api/ prefix when calling by controller name only (e.g., 'Redirect')
        if (!url.startsWith('http://') && !url.startsWith('https://') && !url.startsWith(selectedBaseUrl)) {
            // If the url does not already contain '/api/' prefix, add it
            if (!/^api\//i.test(url)) {
                url = 'api/' + url.replace(/^\//, '');
            }
        }
        
        // Prepend baseUrl if the endpoint is relative
        if (!url.startsWith('http://') && !url.startsWith('https://')) {
            url = (selectedBaseUrl ? selectedBaseUrl.replace(/\/$/, '') : '') + '/' + url.replace(/^\//, '');
        }
        
        // Replace URL parameters
        Object.keys(urlParams).forEach(param => {
            url = url.replace('{' + param + '}', urlParams[param]);
        });
        
        // Add query parameters
        if (Object.keys(queryParams).length > 0) {
            const params = new URLSearchParams(queryParams);
            url += (url.includes('?') ? '&' : '?') + params.toString();
        }
        
        // Add /api/ prefix if needed
        if (!url.startsWith('http://') && !url.startsWith('https://') && !url.startsWith(baseUrl)) {
            if (!/^api\//i.test(url)) {
                url = 'api/' + url.replace(/^\//, '');
            }
            url = (baseUrl ? baseUrl.replace(/\/$/, '') : '') + '/' + url.replace(/^\//, '');
        }
        
        return url;
    }
    
    /**
     * Verify a secret key against the API using the new backend authentication system
     * @param {string} secretKey - The secret key to verify
     * @param {string} domain - The current domain
     * @returns {Promise} - Promise resolving to the verification response
     */
    function verifySecretKey(secretKey, domain) {
        return new Promise((resolve, reject) => {
            // Use WordPress AJAX to verify through our backend auth manager
            $.ajax({
                url: resolveAjaxUrl(),
                type: 'POST',
                data: {
                    action: 'aysa_verify_secret_key',
                    secret_key: secretKey,
                    domain: domain,
                    nonce: resolveAuthNonce()
                },
                success: function(response) {
                    if (response.success) {
                        // Store user IDs from response
                        wp_user_id = response.data.wp_user_id;
                        aysa_user_id = response.data.aysa_user_id;
                        
                        console.log('[AysaAPI] Authentication successful');
                        resolve(response.data);
                    } else {
                        reject(new Error(response.data || 'Verification failed'));
                    }
                },
                error: function(xhr, status, error) {
                    console.error('[AysaAPI] Verification request failed:', { status, error });
                    reject(new Error('Network error during verification'));
                }
            });
        });
    }
    
    /**
     * Check authentication status using the backend auth manager
     * @returns {Promise} - Promise resolving to the authentication status
     */
    function checkAuthStatus() {
        return new Promise((resolve, reject) => {
            $.ajax({
                url: resolveAjaxUrl(),
                type: 'POST',
                data: {
                    action: 'aysa_get_auth_status',
                    nonce: resolveAuthNonce()
                },
                success: function(response) {
                    if (response.success) {
                        if (response.data.authenticated) {
                            wp_user_id = response.data.wp_user_id;
                            aysa_user_id = response.data.aysa_user_id;
                        } else {
                            wp_user_id = null;
                            aysa_user_id = null;
                        }
                        resolve(response.data);
                    } else {
                        reject(new Error(response.data || 'Status check failed'));
                    }
                },
                error: function(xhr, status, error) {
                    const message = parseAjaxErrorMessage(xhr);
                    const isExpectedUnauthenticated = xhr && Number(xhr.status) === 403;
                    if (isExpectedUnauthenticated) {
                        wp_user_id = null;
                        aysa_user_id = null;
                        resolve({
                            authenticated: false,
                            wp_user_id: null,
                            aysa_user_id: null,
                            source: 'forbidden'
                        });
                        return;
                    }
                    console.error('[AysaAPI] Auth status check failed:', { status, error });
                    reject(new Error(message || 'Network error during auth status check'));
                }
            });
        });
    }
    
    /**
     * Logout using the backend auth manager
     * @returns {Promise} - Promise resolving when logout is complete
     */
    function logout() {
        return new Promise((resolve, reject) => {
            $.ajax({
                url: resolveAjaxUrl(),
                type: 'POST',
                data: {
                    action: 'aysa_logout',
                    nonce: resolveAuthNonce()
                },
                success: function(response) {
                    if (response.success) {
                        // Clear stored user IDs
                        wp_user_id = null;
                        aysa_user_id = null;
                        
                        console.log('[AysaAPI] Logout successful');
                        resolve(response.data);
                    } else {
                        reject(new Error(response.data || 'Logout failed'));
                    }
                },
                error: function(xhr, status, error) {
                    console.error('[AysaAPI] Logout request failed:', { status, error });
                    reject(new Error('Network error during logout'));
                }
            });
        });
    }
    
    /**
     * Get data from an API endpoint using endpoint name
     * @param {string} endpointName - The name of the endpoint from configuration
     * @param {object} urlParams - Parameters to replace in URL
     * @param {object} queryParams - Query parameters to append
     * @returns {Promise} - Promise resolving to the API response
     */
    function getDataByEndpoint(endpointName, urlParams = {}, queryParams = {}) {
        return new Promise((resolve, reject) => {
            const url = getEndpointUrl(endpointName, urlParams, queryParams);
            
            if (!url) {
                reject(new Error('Invalid endpoint: ' + endpointName));
                return;
            }
            
            console.log('[AysaAPI] GET:', url);
            
            $.ajax({
                url: url,
                type: 'GET',
                contentType: 'application/json',
                dataType: 'json',
                success: function(response) {
                    // Track API call for credit monitoring
                    if (typeof AysaCreditTracker !== 'undefined') {
                        AysaCreditTracker.trackApiCall(url, 'GET');
                    }
                    resolve(response);
                },
                error: function(xhr) {
                    reject(xhr);
                }
            });
        });
    }
    
    /**
     * Post data to an API endpoint using endpoint name
     * @param {string} endpointName - The name of the endpoint from configuration
     * @param {object} data - The data to post
     * @param {object} urlParams - Parameters to replace in URL
     * @param {object} queryParams - Query parameters to append
     * @returns {Promise} - Promise resolving to the API response
     */
    function postDataByEndpoint(endpointName, data, urlParams = {}, queryParams = {}) {
        return new Promise((resolve, reject) => {
            const url = getEndpointUrl(endpointName, urlParams, queryParams);
            
            if (!url) {
                reject(new Error('Invalid endpoint: ' + endpointName));
                return;
            }
            
            console.log('[AysaAPI] POST:', url);
            
            $.ajax({
                url: url,
                type: 'POST',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify(data),
                success: function(response) {
                    // Track API call for credit monitoring
                    if (typeof AysaCreditTracker !== 'undefined') {
                        AysaCreditTracker.trackApiCall(url, 'POST');
                    }
                    resolve(response);
                },
                error: function(xhr) {
                    reject(xhr);
                }
            });
        });
    }
    
    /**
     * Delete data at an API endpoint using endpoint name
     * @param {string} endpointName - The name of the endpoint from configuration
     * @param {object} urlParams - Parameters to replace in URL
     * @param {object} queryParams - Query parameters to append
     * @returns {Promise} - Promise resolving to the API response
     */
    function deleteDataByEndpoint(endpointName, urlParams = {}, queryParams = {}) {
        return new Promise((resolve, reject) => {
            const url = getEndpointUrl(endpointName, urlParams, queryParams);
            
            if (!url) {
                reject(new Error('Invalid endpoint: ' + endpointName));
                return;
            }
            
            console.log('[AysaAPI] DELETE:', url);
            
            $.ajax({
                url: url,
                type: 'DELETE',
                contentType: 'application/json',
                success: function(response) {
                    // Track API call for credit monitoring
                    if (typeof AysaCreditTracker !== 'undefined') {
                        AysaCreditTracker.trackApiCall(url, 'DELETE');
                    }
                    resolve(response);
                },
                error: function(xhr) {
                    reject(xhr);
                }
            });
        });
    }
    
    /**
     * Get data from a specific API endpoint (legacy method)
     * @param {string} endpoint - The API endpoint
     * @returns {Promise} - Promise resolving to the API response
     */
    function getData(endpoint) {
        return new Promise((resolve, reject) => {
            // Normalize endpoint with baseUrl if needed
            let url = endpoint;
            if (!url.startsWith('http://') && !url.startsWith('https://')) {
                url = (baseUrl ? baseUrl.replace(/\/$/, '') : '') + '/' + url.replace(/^\//, '');
            }
            console.log('[AysaAPI] GET (legacy):', url);
            
            $.ajax({
                url: url,
                type: 'GET',
                contentType: 'application/json',
                dataType: 'json',
                success: function(response) {
                    // Track API call for credit monitoring
                    if (typeof AysaCreditTracker !== 'undefined') {
                        AysaCreditTracker.trackApiCall(url, 'GET');
                    }
                    resolve(response);
                },
                error: function(xhr) {
                    reject(xhr);
                }
            });
        });
    }
    
    /**
     * Post data to a specific API endpoint (legacy method)
     * @param {string} endpoint - The API endpoint
     * @param {object} data - The data to post
     * @returns {Promise} - Promise resolving to the API response
     */
    function postData(endpoint, data) {
        return new Promise((resolve, reject) => {
            let url = endpoint;
            if (!url.startsWith('http://') && !url.startsWith('https://')) {
                if (!/^api\//i.test(url)) {
                    url = 'api/' + url.replace(/^\//, '');
                }
                url = (baseUrl ? baseUrl.replace(/\/$/, '') : '') + '/' + url.replace(/^\//, '');
            }
            console.log('[AysaAPI] POST (legacy):', url);
            
            $.ajax({
                url: url,
                type: 'POST',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify(data),
                success: function(response) {
                    // Track API call for credit monitoring
                    if (typeof AysaCreditTracker !== 'undefined') {
                        AysaCreditTracker.trackApiCall(url, 'POST');
                    }
                    resolve(response);
                },
                error: function(xhr) {
                    reject(xhr);
                }
            });
        });
    }
    
    /**
     * Delete data at a specific API endpoint (legacy method)
     * @param {string} endpoint - The API endpoint
     * @returns {Promise} - Promise resolving to the API response
     */
    function deleteData(endpoint) {
        return new Promise((resolve, reject) => {
            let url = endpoint;
            if (!url.startsWith('http://') && !url.startsWith('https://')) {
                if (!/^api\//i.test(url)) {
                    url = 'api/' + url.replace(/^\//, '');
                }
                url = (baseUrl ? baseUrl.replace(/\/$/, '') : '') + '/' + url.replace(/^\//, '');
            }
            console.log('[AysaAPI] DELETE (legacy):', url);
            
            $.ajax({
                url: url,
                type: 'DELETE',
                contentType: 'application/json',
                success: function(response) {
                    // Track API call for credit monitoring
                    if (typeof AysaCreditTracker !== 'undefined') {
                        AysaCreditTracker.trackApiCall(url, 'DELETE');
                    }
                    resolve(response);
                },
                error: function(xhr) {
                    reject(xhr);
                }
            });
        });
    }
    
    /**
     * Get the current Aysa user ID (from external API)
     * @returns {number|null} - The Aysa user ID or null if not authenticated
     */
    function getAysaUserId() {
        return aysa_user_id;
    }
    
    /**
     * Get the current WordPress user ID
     * @returns {number|null} - The WordPress user ID or null if not authenticated
     */
    function getWordPressUserId() {
        return wp_user_id;
    }
    
    /**
     * Get the API configuration
     * @returns {object} - The API configuration object
     */
    function getConfig() {
        return {
            endpoints: apiEndpoints,
            baseUrl: baseUrl,
            wp_user_id: wp_user_id,
            aysa_user_id: aysa_user_id,
            authenticated: aysa_user_id !== null && wp_user_id !== null
        };
    }
    
    /**
     * Public API
     */
    return {
        init: init,
        verifySecretKey: verifySecretKey,
        checkAuthStatus: checkAuthStatus,
        logout: logout,
        
        // New methods using endpoint names
        getEndpointUrl: getEndpointUrl,
        getDataByEndpoint: getDataByEndpoint,
        postDataByEndpoint: postDataByEndpoint,
        deleteDataByEndpoint: deleteDataByEndpoint,
        
        // Legacy methods for backward compatibility
        getData: getData,
        postData: postData,
        deleteData: deleteData,
        
        // Updated user ID methods
        getAysaUserId: getAysaUserId,
        getWordPressUserId: getWordPressUserId,
        getUserId: getAysaUserId, // Legacy alias for backward compatibility
        getConfig: getConfig
    };
    
})(jQuery);

// Initialize API service when document is ready
jQuery(document).ready(function() {
    AysaAPI.init();
}); 
