import { fetchWithAuth } from '../fetchWithAuth';

const API_BASE_URL = import.meta.env.VITE_EFC_API_URL;

export const fetchPedimentoCoves = async (pedimentoId, page = 1, pageSize = 10, filters = {}) => {
  try {
    const params = new URLSearchParams({
      pedimento: pedimentoId,
      page: page.toString(),
      page_size: pageSize.toString(),
    });

    // Agregar filtros si existen
    if (filters.numero_cove) {
      params.append('numero_cove__icontains', filters.numero_cove);
    }
    if (filters.cove_descargado !== undefined && filters.cove_descargado !== '') {
      params.append('cove_descargado', filters.cove_descargado);
    }
    if (filters.acuse_cove_descargado !== undefined && filters.acuse_cove_descargado !== '') {
      params.append('acuse_cove_descargado', filters.acuse_cove_descargado);
    }
    if (filters.date_from) {
      params.append('created_at__gte', filters.date_from);
    }
    if (filters.date_to) {
      params.append('created_at__lte', filters.date_to);
    }

    const response = await fetchWithAuth(`${API_BASE_URL}/customs/coves/?${params}`);
    
    if (!response.ok) {
      throw new Error(`Error ${response.status}: ${response.statusText}`);
    }

    const data = await response.json();
    return {
      results: data.results,
      count: data.count,
      next: data.next,
      previous: data.previous
    };
  } catch (error) {
    console.error('Error fetching COVEs:', error);
    throw error;
  }
};

export const downloadCove = async (coveId) => {
  try {
    const response = await fetchWithAuth(`${API_BASE_URL}/customs/coves/${coveId}/download/`);
    
    if (!response.ok) {
      throw new Error(`Error ${response.status}: ${response.statusText}`);
    }

    const blob = await response.blob();
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    a.download = `COVE_${coveId}.pdf`;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
  } catch (error) {
    console.error('Error downloading COVE:', error);
    throw error;
  }
};

export const downloadAcuseCove = async (coveId) => {
  try {
    const response = await fetchWithAuth(`${API_BASE_URL}/customs/coves/${coveId}/download-acuse/`);
    
    if (!response.ok) {
      throw new Error(`Error ${response.status}: ${response.statusText}`);
    }

    const blob = await response.blob();
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    a.download = `ACUSE_COVE_${coveId}.pdf`;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
  } catch (error) {
    console.error('Error downloading COVE acuse:', error);
    throw error;
  }
};