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

export interface WinsaaiGenerationRequest {
    invoice_ids: number[];
    is_temporal: boolean;
}

export interface WinsaaiResponse {
    task_id: string;
    status: string;
    message: string;
}

export const reportsWinsaaiApi = {
    invoices: {
        triggerGeneration: async (payload: WinsaaiGenerationRequest): Promise<WinsaaiResponse> => {
            const token = localStorage.getItem('access_token');
            const response = await fetch(`${BASE_URL}/v1/a76/reports/importacion/winsaai/invoices/generate`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(payload)
            });
                    if (!response.ok) {
            let errorMessage = 'Error al iniciar la generación WINSAAI de facturas';
            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): Promise<any> => {
            const token = localStorage.getItem('access_token');
            const response = await fetch(`${BASE_URL}/v1/a76/reports/importacion/winsaai/invoices/status/${taskId}`, {
                method: 'GET',
                headers: { 'Authorization': `Bearer ${token}` }
            });
                    if (!response.ok) {
            let errorMessage = 'Error al consultar estado WINSAAI de facturas';
            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();
        },

        downloadFile: async (taskId: string): Promise<Response> => {
            const token = localStorage.getItem('access_token');
            return await fetch(`${BASE_URL}/v1/a76/reports/importacion/winsaai/invoices/download/${taskId}`, {
                method: 'GET',
                headers: { 'Authorization': `Bearer ${token}` }
            });
        }
    },

    pedimentos: {
        triggerGeneration: async (pedimentoIds: number[], isTemporal: boolean = true, isByClass: boolean = false): Promise<WinsaaiResponse> => {
            const token = localStorage.getItem('access_token');
            const response = await fetch(`${BASE_URL}/v1/a76/reports/importacion/winsaai/pedimentos/generate`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    pedimento_ids: pedimentoIds,
                    is_temporal: isTemporal,
                    is_by_class: isByClass
                })
            });
                    if (!response.ok) {
            let errorMessage = 'Error al iniciar la generación WINSAAI de pedimentos';
            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): Promise<any> => {
            const token = localStorage.getItem('access_token');
            const response = await fetch(`${BASE_URL}/v1/a76/reports/importacion/winsaai/pedimentos/status/${taskId}`, {
                method: 'GET',
                headers: { 'Authorization': `Bearer ${token}` }
            });
                    if (!response.ok) {
            let errorMessage = 'Error al consultar estado WINSAAI de pedimentos';
            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();
        },

        downloadFile: async (taskId: string): Promise<Response> => {
            const token = localStorage.getItem('access_token');
            return await fetch(`${BASE_URL}/v1/a76/reports/importacion/winsaai/pedimentos/download/${taskId}`, {
                method: 'GET',
                headers: { 'Authorization': `Bearer ${token}` }
            });
        }
    }
};
