import { api } from '$lib/api';
import { companyStore } from '$lib/stores/company.svelte'; // <--- NUEVO: Importamos el store para el fallback
import type { ApiResponse } from '$lib/api';

export interface CustomsBroker {
    id: number;
    type?: string | null;
    broker_key: string;
    name?: string | null;
    address?: string | null;
    postal_code?: string | null;
    city?: string | null;
    state?: string | null;
    phone?: string | null;
    fax?: string | null;
    email?: string | null;
    country?: string | null;
    tax_id?: string | null;
    personal_id?: string | null;
    position?: string | null;
    license: string;
    company?: string | null;
    contact?: string | null;
    tenant_id: string;
    company_id: string;
    vu?: CustomsBrokerVU | null;
}

export interface CustomsBrokerVU {
    tenant_id?: string | null;
    company_id?: string | null;
    certificate_path?: string | null;
    key_path?: string | null;
    access_key?: string | null;
    fiel_format?: string | null;
    signature_read_path?: string | null;
    archive_path?: string | null;
    fiel_access_key?: string | null;
    web_service_user?: string | null;
    web_service_access_key?: string | null;
    vu_email?: string | null;
    vu_figure_type?: string | null;
    xml_files_path?: string | null;
    query_tax_id?: string | null;
    doda_certificate_path?: string | null;
    doda_key_path?: string | null;
    doda_web_service_user?: string | null;
    doda_web_service_access_key?: string | null;
    doda_fiel_access_key?: string | null;
    doda_xml_files_path?: string | null;
}

export interface CustomsBrokerPersonnel {
    broker_key: string;
    line: number;
    name?: string | null;
    tax_id?: string | null;
    personal_id?: string | null;
    position?: string | null;
    license?: string | null;
    first_name?: string | null;
    last_name?: string | null;
    middle_name?: string | null;
    email?: string | null;
}

export interface CreateCustomsBrokerData {
    type?: string | null;
    broker_key: string;
    name?: string | null;
    address?: string | null;
    postal_code?: string | null;
    city?: string | null;
    state?: string | null;
    phone?: string | null;
    fax?: string | null;
    email?: string | null;
    country?: string | null;
    tax_id?: string | null;
    personal_id?: string | null;
    position?: string | null;
    license?: string | null;
    company?: string | null;
    contact?: string | null;
    tenant_id?: string;
    company_id: string;
}

export interface CustomsBrokerListResponse {
    items: CustomsBroker[];
    total: number;
    page: number;
    page_size: number;
}

/**
 * API para Agentes Aduanales
 */
export const customsBrokersApi = {
    list: (companyId: string, page = 1, pageSize = 50) => {
        return api.get<CustomsBrokerListResponse>(
            `/v1/a76/customs-brokers?company_id=${companyId}&page=${page}&page_size=${pageSize}`
        );
    },

    get: (brokerKey: string, companyId: string) => {
        return api.get<CustomsBroker>(`/v1/a76/customs-brokers/${brokerKey}?company_id=${companyId}`);
    },

    create: (data: CreateCustomsBrokerData, companyId: string) => {
        return api.post<CustomsBroker>(`/v1/a76/customs-brokers/?company_id=${companyId}`, data);
    },

    /**
     * Actualiza la información de un agente aduanal
     */
    update: (brokerKey: string, data: CreateCustomsBrokerData) => {
        const companyId = data.company_id;
        return api.put<CustomsBroker>(
            `/v1/a76/customs-brokers/${brokerKey}/?company_id=${companyId}`,
            data
        );
    },

    /**
     * Elimina un agente aduanal
     */
    delete: (brokerKey: string, companyId: string) => {
        return api.delete<CustomsBroker>(
            `/v1/a76/customs-brokers/${brokerKey}?company_id=${companyId}`
        );
    },

    /**
     * Actualiza la información de Ventanilla Única (VU)
     */
    updateVU: (brokerKey: string, data: CustomsBrokerVU, companyId: string) => {
        // LOGICA DE RESCATE:
        // Si companyId llega nulo/undefined, intentamos obtenerlo del store global
        let finalCompanyId = companyId;

        if (!finalCompanyId && companyStore.activeCompany?.id) {
            finalCompanyId = companyStore.activeCompany.id.toString();
            console.warn("WARN: companyId no fue provisto a updateVU, usando companyStore:", finalCompanyId);
        }

        // Aseguramos que el payload tenga los IDs
        const payload = {
            ...data,
            company_id: finalCompanyId,
            tenant_id: finalCompanyId
        };

        console.log('[DEBUG] Enviando payload VU:', payload);

        return api.put<CustomsBrokerVU>(
            `/v1/a76/customs-broker-vu/${brokerKey}?company_id=${finalCompanyId}`,
            payload
        );
    },

    updatePersonnel: (brokerKey: string, line: number, data: CustomsBrokerPersonnel, companyId: string) => {
        return api.put<CustomsBrokerPersonnel>(
            `/v1/a76/customs-broker-personnel/${brokerKey}/${line}?company_id=${companyId}`,
            data
        );
    }
};