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';
import { getToken } from '$lib/auth';

export type VuUploadFileKind =
	| 'certificate'
	| 'key'
	| 'cove'
	| 'doda_certificate'
	| 'doda_key'
	| 'doda_cove';

export interface CustomsBrokerVuUploadResult {
	message: string;
	file_kind: string;
	field: string;
	path: string;
	broker_key: string;
	company_id: number;
}

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;
}

/** Etiqueta para listas/selects cuando `name` viene vacío (clave, patente o id). */
export function displayCustomsBrokerLabel(b: CustomsBroker): string {
    const n = b.name?.trim();
    if (n) return n;
    const key = b.broker_key?.trim();
    if (key) return key;
    const lic = b.license?.trim();
    if (lic) return lic;
    return `#${b.id}`;
}

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);
        }

        // No enviar tenant_id/company_id en payload VU:
        // el backend los resuelve por token + query param.
        const payload = {
            ...data
        };

        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
        );
    }
};

/**
 * Sube CER, KEY o COVE del VU al bucket (MinIO: tenants/.../customs_brokers/...).
 */
export async function uploadCustomsBrokerVuFile(
	brokerKey: string,
	companyId: string,
	fileKind: VuUploadFileKind,
	file: File
): Promise<ApiResponse<CustomsBrokerVuUploadResult>> {
	const formData = new FormData();
	formData.append('file', file);
	const token = getToken();
	const API_BASE_URL = (import.meta.env.VITE_API_URL || '').replace(/\/+$/, '');
	const q = new URLSearchParams({
		company_id: companyId,
		file_kind: fileKind
	});
	const response = await fetch(
		`${API_BASE_URL}/v1/a76/customs-brokers/${encodeURIComponent(brokerKey)}/vu/upload?${q.toString()}`,
		{
			method: 'POST',
			headers: token ? { Authorization: `Bearer ${token}` } : {},
			body: formData,
			credentials: 'include'
		}
	);
	const data = await response.json().catch(() => ({}));
	if (!response.ok) {
		return {
			error: (data as { detail?: string }).detail || (data as { message?: string }).message || 'Error al subir el archivo VU',
			status: response.status
		};
	}
	return { data: data as CustomsBrokerVuUploadResult, status: response.status };
}