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

// Tipos para la respuesta y registros
export interface Task {
  task_id: string;
  timestamp: string;
  message: string;
  status: string;
  pedimento: string;
  organizacion: string;
  servicio: number;
}

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

// API para tasks/tasks/
export async function fetchTasks(
  page: number = 1,
  pageSize: number = 20,
  filters: Record<string, any> = {}
): Promise<TasksResponse> {
  try {
    const API_URL = (import.meta as any).env.VITE_EFC_API_URL;
    
    // Construir query params
    const params = new URLSearchParams();
    params.append('page', String(page));
    params.append('page_size', String(pageSize));
    
    // Agregar filtros
    Object.entries(filters).forEach(([key, value]) => {
      if (value !== undefined && value !== null && value !== '') {
        params.append(key, String(value));
      }
    });
    
    const res = await fetchWithAuth(`${API_URL}/tasks/tasks/?${params.toString()}`);
    
    if (!res.ok) {
      throw new Error('Error al obtener tareas');
    }
    
    return await res.json();
  } catch (error) {
    console.error('Error in fetchTasks:', error);
    throw error;
  }
}
