import { api } from '$lib/api';

// --- Interfaces para Tablas Hijas ---

export interface ClientProviderAddress {
    id?: number;
    streets?: string | null;
    exterior_number?: string | null;
    interior_number?: string | null;
    neighborhood?: string | null;
    municipality?: string | null;
    city?: string | null;
    state?: string | null;
    country?: string | null;
    postal_code?: string | null;
    email?: string | null;
    phone?: string | null;
    contact?: string | null;
}

export interface ClientProviderPrograms {
    id?: number;
    program?: string | null;
    program_number?: string | null;
    secon_auth_date?: number | null; // YYYYMMDD
    prosec?: number | null;
    manufacturer_id?: string | null;
    ctpat_svi?: string | null;
    is_certified_company?: string | null;
}

// --- Interfaz Principal ---

export interface ClientProvider {
    id: number;
    rfc: string;
    name: string;
    short_name?: string | null;
    curp?: string | null;
    client_or_provider: 'client' | 'provider' | 'both';
    
    // Campos planos de la tabla principal
    type_nat_foreign?: string | null;
    responsible?: string | null;
    position?: string | null;
    
    is_active?: boolean;
    
    // Relaciones Anidadas
    address?: ClientProviderAddress | null;
    programs?: ClientProviderPrograms | null;
}

export interface ClientProviderListResponse {
    items: ClientProvider[];
    total: number;
    page: number;
    page_size: number;
}

// DTOs de Envío (excluyendo IDs automáticos)
export interface CreateClientProviderData extends Omit<ClientProvider, 'id' | 'address' | 'programs'> {
    address?: ClientProviderAddress | null;
    programs?: ClientProviderPrograms | null;
}

export interface UpdateClientProviderData extends Partial<CreateClientProviderData> {}

export const clientsProvidersApi = {
    list: (companyId: number, page = 1, pageSize = 50, filters?: Record<string, any>) => {
        const params = new URLSearchParams({
            company_id: companyId.toString(),
            page: page.toString(),
            page_size: pageSize.toString()
        });
        if (filters) {
            Object.entries(filters).forEach(([key, value]) => {
                if (value) params.append(key, value.toString());
            });
        }
        return api.get<ClientProviderListResponse>(`/v1/a76/clients-providers/?${params.toString()}`);
    },
    get: (id: number, companyId: number) =>
        api.get<ClientProvider>(`/v1/a76/clients-providers/${id}/?company_id=${companyId}`),
    
    create: (companyId: number, data: any) =>
        api.post<ClientProvider>(`/v1/a76/clients-providers/?company_id=${companyId}`, data),

    update: (id: number, companyId: number, data: any) =>
        api.patch<ClientProvider>(`/v1/a76/clients-providers/${id}?company_id=${companyId}`, data),

    delete: (id: number, companyId: number) =>
        api.delete(`/v1/a76/clients-providers/${id}/?company_id=${companyId}`)
};