// src\api\pedimentoCompleto.ts
import { fetchWithAuth } from '../fetchWithAuth';

export interface PedimentoCompleto {
  id: string;
  organizacion: string;
  pedimento: string;
  pedimento_numero: string;
  archivo: string;
  document_type: number;
  size: number;
  extension: string;
  fuente: number;
  created_at: string;
  updated_at: string;
}

export interface PedimentoCompletoResponse {
  count: number;
  next: string | null;
  previous: string | null;
  results: PedimentoCompleto[];
}

export interface DocumentFilters {
  document_type?: string;
  archivo__icontains?: string;
  extension?: string;
  created_at__date?: string;
  ordering?: string;
}

const API_URL = (import.meta as any).env.VITE_EFC_API_URL;

export async function fetchPedimentoCompleto(
  pedimentoId: string,
  page: number = 1,
  pageSize: number = 10,
  filters: DocumentFilters = {}
): Promise<PedimentoCompletoResponse> {
  try {
    // Construir URL con filtros
    const params = new URLSearchParams({
      page: page.toString(),
      page_size: pageSize.toString(),
      pedimento: pedimentoId
    });
    
    // Agregar filtros si existen
    Object.entries(filters).forEach(([key, value]) => {
      if (value !== undefined && value !== '') {
        params.append(key, value.toString());
      }
    });
    
    // const res = await fetchWithAuth(`${API_URL}/record/documents/?${params.toString()}`);
    const res = await fetchWithAuth(`${API_URL}/record/pedimento-documents/?${params.toString()}`);

    if (!res.ok) {
      throw new Error('No autorizado o error en la petición');
    }
    
    return res.json();
  } catch (error) {
    console.error('Error in fetchPedimentoCompleto:', error);
    throw error;
  }
}
