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

export const invoicesReportsApi = {

    triggerPdfGeneration: async (invoiceId: number, companyId: number, invoiceType: string = 'mexican', currency: string = 'ORIGINAL') => {
        const params = new URLSearchParams({
            company_id: companyId.toString(),
            invoice_type: invoiceType,
            currency_code: currency
        });
        const endpoint = `${BASE_URL}/v1/a76/reports/importacion/facturas/${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) throw new Error('Error al iniciar la generación');
        return await response.json();
    },

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

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

        if (!response.ok) throw new Error('Error al consultar estado');
        return await response.json();
    },

    triggerPackingListGeneration: async (invoiceId: number, companyId: number) => {
        const params = new URLSearchParams({ company_id: companyId.toString() });
        const endpoint = `${BASE_URL}/v1/a76/reports/importacion/packing-lists/${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) throw new Error('Error al iniciar la generación de Packing List');
        return await response.json();
    },

    getPackingListTaskStatus: async (taskId: string) => {
        const endpoint = `${BASE_URL}/v1/a76/reports/importacion/packing-lists/tasks/${taskId}`;

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

        if (!response.ok) throw new Error('Error al consultar estado de Packing List');
        return await response.json();
    }
};