const API_USERNAME = 'admin';
const API_PASSWORD = atob('Mf33ksTRLrPKSqQ4cTXitgiSN6BPBt89');

const Controller = {
    Revenue: "revenue",
    Expense: "expense"
}
function getApiBaseUrl() {
    const isLocal = location.hostname === 'localhost' || location.hostname === '127.0.0.1';
    return isLocal ? 'http://localhost:5018' : 'https://administration.byakurepo.online';
}

function showApiError(errorInfo) {
    console.error("❌ Erreur API :");
    console.error("🔗 URL :", errorInfo.url);
    console.error("📡 Méthode :", errorInfo.method);
    console.error("📄 Code HTTP :", errorInfo.status);
    if (errorInfo.message) console.error("📢 Message :", errorInfo.message);
    if (errorInfo.body) console.error("📦 Contenu retourné :", errorInfo.body);
}

/**
 * 🔁 GET générique
 */
async function apiGet(endpoint, options = {}, onSuccess, onError) {
    const url = getApiBaseUrl() + endpoint;
    const loader = document.getElementById('loader');
    if (loader) loader.style.display = 'block';

    try {
        const response = await fetch(url, {
            method: 'GET',
            headers: {
                'Authorization': 'Basic ' + btoa(`${API_USERNAME}:${API_PASSWORD}`),
                'Content-Type': 'application/json',
                ...options.headers
            },
            ...options
        });

        const responseBody = await response.text();
        if (!response.ok) {
            const errorInfo = {
                url,
                method: 'GET',
                status: response.status,
                message: response.statusText,
                body: responseBody
            };
            showApiError(errorInfo);
            if (onError) onError(errorInfo);
            return;
        }

        const data = JSON.parse(responseBody);
        if (onSuccess) onSuccess(data);
    } catch (error) {
        showApiError({ url, method: 'GET', status: 0, message: error.message });
        if (onError) onError(error);
    } finally {
        if (loader) loader.style.display = 'none';
    }
}

/**
 * 🔁 POST générique
 */
async function apiPost(endpoint, body = {}, onSuccess, onError) {
    const url = getApiBaseUrl() + endpoint;
    const loader = document.getElementById('loader');
    if (loader) loader.style.display = 'block';

    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Authorization': 'Basic ' + btoa(`${API_USERNAME}:${API_PASSWORD}`),
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(body)
        });

        const responseBody = await response.text();
        if (!response.ok) {
            const errorInfo = {
                url,
                method: 'POST',
                status: response.status,
                message: response.statusText,
                body: responseBody
            };
            showApiError(errorInfo);
            if (onError) onError(errorInfo);
            return;
        }

        const data = JSON.parse(responseBody);
        if (onSuccess) onSuccess(data);
    } catch (error) {
        showApiError({ url, method: 'POST', status: 0, message: error.message });
        if (onError) onError(error);
    } finally {
        if (loader) loader.style.display = 'none';
    }
}

/**
 * 🌐 Appel GET d’une ressource/action
 */
function apiCall(resource, action, queryParams = {}, onSuccess, onError) {
    const query = new URLSearchParams(queryParams).toString();
    const endpoint = `/api/${resource}/${action}${query ? `?${query}` : ''}`;
    apiGet(endpoint, {}, onSuccess, onError);
}

/**
 * 🌐 Appel POST d’une ressource/action
 */
function apiPostCall(resource, action, body = {}, onSuccess, onError) {
    const endpoint = `/api/${resource}/${action}`;
    apiPost(endpoint, body, onSuccess, onError);
}
