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

export const consolidatedReportsApi = {

    triggerPdfGeneration: async (invoiceId: number, companyId: number) => {
        const params = new URLSearchParams({ company_id: companyId.toString() });
        const endpoint = `${BASE_URL}/v1/a76/reports/importacion/consolidados/${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 consolidado';
            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/importacion/consolidados/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 consolidado';
            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();
    }
};
