
const BASE_URL = import.meta.env.VITE_API_URL || '';

export const dischargeReportsApi = {

    triggerPdfGeneration: async (invoiceId: number, companyId: number) => {
        const params = new URLSearchParams({ company_id: companyId.toString() });
        // Endpoint matches routes.py
        const endpoint = `${BASE_URL}/v1/a76/reports/exportacion/descargo/${invoiceId}/download-async?${params.toString()}`;

        const token = localStorage.getItem('access_token');
        const response = await fetch(endpoint, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        });

                if (!response.ok) {
            let errorMessage = 'Error al iniciar la generación del Reporte de Descarga';
            try {
                const errorData = await response.json();
                errorMessage = errorData.detail || errorData.message || errorMessage;
            } catch (e) {
                try {
                    const text = await response.text();
                    if (text) errorMessage = text;
                } catch (e2) {}
            }
            throw new Error(errorMessage);
        }
        return await response.json();
    },

    getTaskStatus: async (taskId: string) => {
        const endpoint = `${BASE_URL}/v1/a76/reports/exportacion/descargo/tasks/${taskId}`;

        const token = localStorage.getItem('access_token');
        const response = await fetch(endpoint, {
            method: 'GET',
            headers: { 'Authorization': `Bearer ${token}` }
        });

                if (!response.ok) {
            let errorMessage = 'Error al consultar estado del Reporte de Descarga';
            try {
                const errorData = await response.json();
                errorMessage = errorData.detail || errorData.message || errorMessage;
            } catch (e) {
                try {
                    const text = await response.text();
                    if (text) errorMessage = text;
                } catch (e2) {}
            }
            throw new Error(errorMessage);
        }
        return await response.json();
    },

    assignFifo: async (invoiceId: number) => {
        // Endpoint: /a76/reports/exportacion/descargo/fifo-assign/{invoice_id}
        const endpoint = `${BASE_URL}/v1/a76/reports/exportacion/descargo/fifo-assign/${invoiceId}`;
        const token = localStorage.getItem('access_token');

        try {
            const response = await fetch(endpoint, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                const errData = await response.json().catch(() => ({}));
                return { data: null, error: errData.detail || 'Error al ejecutar PEPS' };
            }

            return { data: await response.json(), error: null };
        } catch (e: any) {
            return { data: null, error: e.message || 'Error de conexión PEPS' };
        }
    }
};
