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

const API_BASE_URL = import.meta.env.VITE_EFC_API_URL;

export const fetchPedimentoEdocuments = 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_edocument) {
      params.append('numero_edocument__icontains', filters.numero_edocument);
    }
    if (filters.clave) {
      params.append('clave__icontains', filters.clave);
    }
    if (filters.descripcion) {
      params.append('descripcion__icontains', filters.descripcion);
    }
    if (filters.edocument_descargado !== undefined && filters.edocument_descargado !== '') {
      params.append('edocument_descargado', filters.edocument_descargado);
    }
    if (filters.acuse_descargado !== undefined && filters.acuse_descargado !== '') {
      params.append('acuse_descargado', filters.acuse_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/edocuments/?${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 EDocs:', error);
    throw error;
  }
};

export const downloadEdocument = async (edocId) => {
  try {
    const response = await fetchWithAuth(`${API_BASE_URL}/customs/edocuments/${edocId}/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 = `EDOC_${edocId}.pdf`;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
  } catch (error) {
    console.error('Error downloading EDocs:', error);
    throw error;
  }
};

export const downloadAcuseEdocument = async (edocId) => {
  try {
    const response = await fetchWithAuth(`${API_BASE_URL}/customs/edocuments/${edocId}/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_EDOC_${edocId}.pdf`;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);
  } catch (error) {
    console.error('Error downloading EDocs acuse:', error);
    throw error;
  }
};