// Configurare API globală
const API_BASE_URL = (() => {
    const globalBase = window.AYSA_API_BASE_URL || (window.aysaApiConfig && window.aysaApiConfig.baseUrl);
    const resolved = (typeof globalBase === 'string' && globalBase.trim() !== '')
        ? globalBase.trim()
        : 'https://api.aysa.ai/';
    return resolved.replace(/\/?$/, '/').replace(/\/api\/?$/, '/api/');
})();
const HISTORY_ENDPOINT = 'History/add';
const API_TIMEOUT = 10000;

/**
 * Trimite datele către API pentru salvare în istoric
 */
function sendHistoryData(data) {
    const url = API_BASE_URL + HISTORY_ENDPOINT;

    console.log('Trimitere date istorice:', data);

    return jQuery.ajax({
        url: url,
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(data),
        timeout: API_TIMEOUT,
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        }
    })
    .then(response => {
        console.log('Salvare cu succes:', response);
        return response;
    })
    .catch(error => {
        console.error('Eroare la salvare:', error);
        throw error;
    });
}

/**
 * Înregistrează un redirect în istoric
 */
function logRedirect({ idIntern, sourceUrl, destinationUrl, projectId, status = 'Auto', entityType = 'Product' }) {
    const data = {
        idIntern,
        entityType,
        changeType: 'create',
        oldData: { url: sourceUrl },
        newData: { url: destinationUrl },
        projectId,
        timestamp: new Date().toISOString(),
        userId: window.aysa_params?.current_user_id || 'unknown'
    };

    return sendHistoryData(data);
}

/**
 * Înregistrează schimbări la sugestiile SEO
 */
function logSeoSuggestions({ idIntern, entityType, oldData, newData, projectId }) {
    const data = {
        idIntern,
        entityType,
        changeType: 'update',
        oldData,
        newData,
        projectId,
        timestamp: new Date().toISOString(),
        userId: window.aysa_params?.current_user_id || 'unknown'
    };

    return sendHistoryData(data);
}

// Export functions to global scope
function logToAuditSystem(data) {
    if (typeof jQuery !== 'undefined' && typeof ajaxurl !== 'undefined') {
        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'aysa_log_audit_action',
                nonce: window.aysaAutomationNonce || '',
                audit_data: data
            },
            success: function(response) {
                if (window.console && window.console.log) {
                    console.log('Audit log entry created:', response);
                }
            },
            error: function(xhr, status, error) {
                if (window.console && window.console.error) {
                    console.error('Failed to create audit log entry:', error);
                }
            }
        });
    }
}

function enhancedLogSeoSuggestions(data) {
    const result = logSeoSuggestions(data);
    
    const auditData = {
        action_type: 'seo_suggestion',
        object_id: data.idIntern,
        object_type: data.entityType,
        old_data: data.oldData,
        new_data: data.newData,
        is_automated: false,
        confidence_score: data.confidence_score || null
    };
    
    logToAuditSystem(auditData);
    
    return result;
}

function enhancedLogRedirect(data) {
    const result = logRedirect(data);
    
    const auditData = {
        action_type: 'redirect_creation',
        object_id: 0,
        object_type: 'redirect',
        old_data: { url: data.fromUrl },
        new_data: { url: data.toUrl, type: data.redirectType },
        is_automated: data.is_automated || false,
        confidence_score: data.confidence_score || null
    };
    
    logToAuditSystem(auditData);
    
    return result;
}

window.aysaVersioningService = {
    logRedirect,
    logSeoSuggestions,
    enhancedLogRedirect,
    enhancedLogSeoSuggestions,
    logToAuditSystem
};
console.log('AYSA Versioning Service script fully executed. window.aysaVersioningService is now:', window.aysaVersioningService, 'typeof logSeoSuggestions:', typeof window.aysaVersioningService?.logSeoSuggestions);
