import { api } from '$lib/api';
import type { ApiResponse } from '$lib/api';
import { getToken } from '$lib/auth';

export interface CompanyAddress {
    id?: number;
    address_type: string;
    street?: string | null;
    exterior_number?: string | null;
    interior_number?: string | null;
    postal_code?: string | null;
    neighborhood?: string | null;
    city?: string | null;
    municipality?: string | null;
    state?: string | null;
    country?: string | null;
    phone?: string | null;
    fax?: string | null;
    email?: string | null;
}

export interface CompanyCertification {
    id?: number;
    is_certified_company?: boolean | null;
    certified_company_registration?: string | null;
    certified_company_start_date?: string | null;
    certified_company_end_date?: string | null;
    annex30_certification_date?: string | null;
    annex30_certification_number?: string | null;
    annex30_modality?: string | null;
    annex30_company_type?: string | null;
    annex30_renewal_date?: string | null;
    annex30_final_certification_date?: string | null;
    is_seciit_company?: boolean | null;
    is_oea_company?: boolean | null;
    neec_company?: boolean | null;
}

export interface CompanyDigitalCertificate {
    id?: number;
    certificate_type: string;
    cer_file_path?: string | null;
    key_file_path?: string | null;
    password?: string | null;
    access_key?: string | null;
    cer_expiration_date?: number | null;
    key_expiration_date?: number | null;
}

export interface CompanyVU {
    id?: number;
    webservice_user?: string | null;
    webservice_password?: string | null;
    email?: string | null;
    figure_type?: string | null;
    central_path?: string | null;
    xml_files_path?: string | null;
    query_rfc?: string | null;
    validation_rfc?: string | null;
    configuration_source?: string | null;
    measurement_units?: string | null;
}

export interface CompanyElectronicAgent {
    id?: number;
    input_folder?: string | null;
    output_folder?: string | null;
    send_mask?: string | null;
    response_mask?: string | null;
    response_extension?: string | null;
    counter_start?: number | null;
    counter_end?: number | null;
    counter_next?: number | null;
}

export interface CompanyPrevalidator {
    id?: number;
    customs?: string | null;
    key?: string | null;
    patent?: string | null;
    description?: string | null;
}

export interface CompanyCFDI {
    id?: number;
    xml_save_path?: string | null;
    cfdi_app_path?: string | null;
    pac_app_path?: string | null;
}

export interface Company {
    id: number;
    tenant_id: number;
    name: string | null;
    rfc: string | null;
    curp?: string | null;
    main_activity: string | null;
    program: string | null;
    program_number: string | null;
    prosec: number | null;
    prosec_authorization: string | null;
    manufacturer_id: string | null;
    broker_company: string | null;
    responsible: string | null;
    responsible_name: string | null;
    responsible_last_name: string | null;
    responsible_mother_last_name: string | null;
    responsible_rfc?: string | null;
    position?: string | null;
    fiscal_deposit?: boolean;
    generate_barcodes_with_fiel?: boolean;
    is_service_company?: boolean;
    order_format_type?: string | null;
    ctpat_svi?: string | null;
    trusted_exporter_number?: string | null;
    logo?: string | null;
    previous_code?: number | null;
    client_name?: string | null;
    subassembly_mode?: string | null;
    inter_db_name?: string | null;
    prevalidator_key?: string | null;
    seventh_amendment?: boolean;
    // Sectores
    sector1?: string | null;
    sector2?: string | null;
    sector3?: string | null;
    // Flags técnicos
    active_labels?: number | null;
    active_fractions?: number | null;
    activate_caat?: number | null;
    trans_interface?: number | null;
    american_costs?: number | null;
    scaf_readonly?: number | null;
    parts_replacement?: number | null;
    activate_facmexame?: number | null;
    part_reference?: number | null;
    international_firm?: number | null;
    // Configuraciones
    ftp_key?: string | null;
    sifra_path?: string | null;
    version_type?: string | null;
    sql_language?: string | null;
    balance_operation_mode?: string | null;
    // Campos de certificación (CompanyCertification aplanado)
    is_certified_company?: boolean | null;
    certified_company_registration?: string | null;
    certified_company_start_date?: string | null;
    certified_company_end_date?: string | null;
    annex30_certification_date?: string | null;
    annex30_certification_number?: string | null;
    annex30_modality?: string | null;
    annex30_company_type?: string | null;
    annex30_renewal_date?: string | null;
    annex30_final_certification_date?: string | null;
    is_seciit_company?: boolean | null;
    is_oea_company?: boolean | null;
    neec_company?: boolean | null;
    // Campos de dirección principal (CompanyAddress - main)
    main_street?: string | null;
    main_exterior_number?: string | null;
    main_interior_number?: string | null;
    main_postal_code?: string | null;
    main_neighborhood?: string | null;
    main_city?: string | null;
    main_municipality?: string | null;
    main_state?: string | null;
    main_country?: string | null;
    main_phone?: string | null;
    main_fax?: string | null;
    main_email?: string | null;
    // Campos de dirección industrial 1 (CompanyAddress - industrial1)
    ind1_street?: string | null;
    ind1_exterior_number?: string | null;
    ind1_interior_number?: string | null;
    ind1_postal_code?: string | null;
    ind1_neighborhood?: string | null;
    ind1_city?: string | null;
    ind1_municipality?: string | null;
    ind1_state?: string | null;
    ind1_country?: string | null;
    ind1_phone?: string | null;
    ind1_fax?: string | null;
    ind1_email?: string | null;
    // Campos de dirección industrial 2 (CompanyAddress - industrial2)
    ind2_street?: string | null;
    ind2_exterior_number?: string | null;
    ind2_interior_number?: string | null;
    ind2_postal_code?: string | null;
    ind2_neighborhood?: string | null;
    ind2_city?: string | null;
    ind2_municipality?: string | null;
    ind2_state?: string | null;
    ind2_country?: string | null;
    ind2_phone?: string | null;
    ind2_fax?: string | null;
    ind2_email?: string | null;
    // Campos de prevalidador (CompanyPrevalidator aplanado)
    prev_customs?: string | null;
    prev_key?: string | null;
    prev_patent?: string | null;
    prev_description?: string | null;
    // Campos de ventanilla única (CompanyVU aplanado)
    vu_webservice_user?: string | null;
    vu_webservice_password?: string | null;
    vu_email?: string | null;
    vu_figure_type?: string | null;
    vu_central_path?: string | null;
    vu_xml_files_path?: string | null;
    vu_query_rfc?: string | null;
    vu_validation_rfc?: string | null;
    vu_configuration_source?: string | null;
    vu_measurement_units?: string | null;
    // Campos de agente aduanal electrónico (CompanyElectronicAgent aplanado)
    ea_input_folder?: string | null;
    ea_output_folder?: string | null;
    ea_send_mask?: string | null;
    ea_response_mask?: string | null;
    ea_response_extension?: string | null;
    ea_counter_start?: number | null;
    ea_counter_end?: number | null;
    ea_counter_next?: number | null;
    // Campos de CFDI (CompanyCFDI aplanado)
    cfdi_xml_save_path?: string | null;
    cfdi_app_path?: string | null;
    cfdi_pac_app_path?: string | null;
    // Digital Certificates (Flattened)
    fiel_cer?: string | null;
    fiel_key?: string | null;
    fiel_pass?: string | null;
    fiel_access?: string | null;
    fiel_cer_exp?: number | null;
    fiel_key_exp?: number | null;
    cfdi_cert_cer?: string | null;
    cfdi_cert_key?: string | null;
    cfdi_cert_pass?: string | null;
    cfdi_cert_access?: string | null;
    cfdi_cert_cer_exp?: number | null;
    cfdi_cert_key_exp?: number | null;
    cancel_cer?: string | null;
    cancel_key?: string | null;
    cancel_pass?: string | null;
    cancel_access?: string | null;
    cancel_cer_exp?: number | null;
    cancel_key_exp?: number | null;
    // Submodelos

    addresses?: CompanyAddress[];
    certification?: CompanyCertification | null;
    digital_certificates?: CompanyDigitalCertificate[];
    ventanilla_unica?: CompanyVU | null;
    electronic_agent?: CompanyElectronicAgent | null;
    prevalidator?: CompanyPrevalidator | null;
    cfdi?: CompanyCFDI | null;
    created_at: string | null;
    updated_at: string | null;
}

export interface CompanyCreate {
    name?: string | null;
    rfc?: string | null;
    curp?: string | null;
    main_activity?: string | null;
    program?: string | null;
    program_number?: string | null;
    prosec?: number | null;
    prosec_authorization?: string | null;
    manufacturer_id?: string | null;
    broker_company?: string | null;
    responsible?: string | null;
    responsible_name?: string | null;
    responsible_last_name?: string | null;
    responsible_mother_last_name?: string | null;
    responsible_rfc?: string | null;
    position?: string | null;
    fiscal_deposit?: boolean;
    generate_barcodes_with_fiel?: boolean;
    is_service_company?: boolean;
    order_format_type?: string | null;
    ctpat_svi?: string | null;
    trusted_exporter_number?: string | null;
    logo?: string | null;
    previous_code?: number | null;
    client_name?: string | null;
    subassembly_mode?: string | null;
    inter_db_name?: string | null;
    prevalidator_key?: string | null;
    seventh_amendment?: boolean;
    // Digital Certificates
    fiel_cer?: string | null;
    fiel_key?: string | null;
    fiel_pass?: string | null;
    fiel_access?: string | null;
    fiel_cer_exp?: number | null;
    fiel_key_exp?: number | null;
    cfdi_cert_cer?: string | null;
    cfdi_cert_key?: string | null;
    cfdi_cert_pass?: string | null;
    cfdi_cert_access?: string | null;
    cfdi_cert_cer_exp?: number | null;
    cfdi_cert_key_exp?: number | null;
    cancel_cer?: string | null;
    cancel_key?: string | null;
    cancel_pass?: string | null;
    cancel_access?: string | null;
    cancel_cer_exp?: number | null;
    cancel_key_exp?: number | null;
    // Sectores

    sector1?: string | null;
    sector2?: string | null;
    sector3?: string | null;
    // Flags técnicos
    active_labels?: number | null;
    active_fractions?: number | null;
    activate_caat?: number | null;
    trans_interface?: number | null;
    american_costs?: number | null;
    scaf_readonly?: number | null;
    parts_replacement?: number | null;
    activate_facmexame?: number | null;
    part_reference?: number | null;
    international_firm?: number | null;
    // Configuraciones
    ftp_key?: string | null;
    sifra_path?: string | null;
    version_type?: string | null;
    sql_language?: string | null;
    balance_operation_mode?: string | null;
    // Campos de certificación
    is_certified_company?: boolean | null;
    certified_company_registration?: string | null;
    certified_company_start_date?: string | null;
    certified_company_end_date?: string | null;
    annex30_certification_date?: string | null;
    annex30_certification_number?: string | null;
    annex30_modality?: string | null;
    annex30_company_type?: string | null;
    annex30_renewal_date?: string | null;
    annex30_final_certification_date?: string | null;
    is_seciit_company?: boolean | null;
    is_oea_company?: boolean | null;
    neec_company?: boolean | null;
    // Campos de dirección principal
    main_street?: string | null;
    main_exterior_number?: string | null;
    main_interior_number?: string | null;
    main_postal_code?: string | null;
    main_neighborhood?: string | null;
    main_city?: string | null;
    main_municipality?: string | null;
    main_state?: string | null;
    main_country?: string | null;
    main_phone?: string | null;
    main_fax?: string | null;
    main_email?: string | null;
    // Campos de dirección industrial 1
    ind1_street?: string | null;
    ind1_exterior_number?: string | null;
    ind1_interior_number?: string | null;
    ind1_postal_code?: string | null;
    ind1_neighborhood?: string | null;
    ind1_city?: string | null;
    ind1_municipality?: string | null;
    ind1_state?: string | null;
    ind1_country?: string | null;
    ind1_phone?: string | null;
    ind1_fax?: string | null;
    ind1_email?: string | null;
    // Campos de dirección industrial 2
    ind2_street?: string | null;
    ind2_exterior_number?: string | null;
    ind2_interior_number?: string | null;
    ind2_postal_code?: string | null;
    ind2_neighborhood?: string | null;
    ind2_city?: string | null;
    ind2_municipality?: string | null;
    ind2_state?: string | null;
    ind2_country?: string | null;
    ind2_phone?: string | null;
    ind2_fax?: string | null;
    ind2_email?: string | null;
    // Campos de prevalidador
    prev_customs?: string | null;
    prev_key?: string | null;
    prev_patent?: string | null;
    prev_description?: string | null;
    // Campos de ventanilla única
    vu_webservice_user?: string | null;
    vu_webservice_password?: string | null;
    vu_email?: string | null;
    vu_figure_type?: string | null;
    vu_central_path?: string | null;
    vu_xml_files_path?: string | null;
    vu_query_rfc?: string | null;
    vu_validation_rfc?: string | null;
    vu_configuration_source?: string | null;
    vu_measurement_units?: string | null;
    // Campos de agente aduanal electrónico
    ea_input_folder?: string | null;
    ea_output_folder?: string | null;
    ea_send_mask?: string | null;
    ea_response_mask?: string | null;
    ea_response_extension?: string | null;
    ea_counter_start?: number | null;
    ea_counter_end?: number | null;
    ea_counter_next?: number | null;
    // Campos de CFDI
    cfdi_xml_save_path?: string | null;
    cfdi_app_path?: string | null;
    cfdi_pac_app_path?: string | null;
}

export interface CompanyUpdate extends CompanyCreate { }


export interface CompanyListResponse {
    items: Company[];
    total: number;
    page: number;
    page_size: number;
    pages: number;
}

export async function getCompanies(
    page = 1,
    pageSize = 50,
    filters: Record<string, any> = {}
): Promise<ApiResponse<CompanyListResponse>> {
    const queryParams = new URLSearchParams({
        page: page.toString(),
        page_size: pageSize.toString(),
        ...filters
    });
    return await api.get(`/v1/a76/company?${queryParams.toString()}`);
}

export async function getCompany(id: number): Promise<ApiResponse<Company>> {
    return await api.get(`/v1/a76/company/${id}`);
}

export async function createCompany(data: CompanyCreate): Promise<ApiResponse<Company>> {
    return await api.post(`/v1/a76/company`, data);
}

export async function updateCompany(id: number, data: CompanyUpdate): Promise<ApiResponse<Company>> {
    return await api.put(`/v1/a76/company/${id}`, data);
}

export async function deleteCompany(id: number): Promise<ApiResponse<void>> {
    return await api.delete(`/v1/a76/company/${id}`);
}

export async function uploadCompanyLogo(id: number, file: File): Promise<ApiResponse<{ message: string; logo_path: string; company_id: number }>> {
    const formData = new FormData();
    formData.append('file', file);

    // Para FormData, usamos fetch directamente ya que necesitamos omitir Content-Type
    // para que el navegador establezca el boundary automáticamente
    const token = getToken();
    const API_BASE_URL = (import.meta.env.VITE_API_URL || '').replace(/\/+$/, '');

    const response = await fetch(`${API_BASE_URL}/v1/a76/company/${id}/upload-logo`, {
        method: 'POST',
        headers: token ? { Authorization: `Bearer ${token}` } : {},
        body: formData,
        credentials: 'include'
    });

    const data = await response.json();

    if (!response.ok) {
        return {
            error: data.detail || data.message || 'Error al subir el logo',
            status: response.status
        };
    }

    return {
        data,
        status: response.status
    };
}

export async function uploadCompanyCertificate(id: number, type: string, file: File, password?: string): Promise<ApiResponse<{ message: string; file_path: string; certificate_type: string; company_id: number }>> {
    const formData = new FormData();
    formData.append('file', file);
    if (password) {
        formData.append('password', password);
    }

    const token = getToken();
    const API_BASE_URL = (import.meta.env.VITE_API_URL || '').replace(/\/+$/, '');

    const response = await fetch(`${API_BASE_URL}/v1/a76/company/${id}/upload-certificate?certificate_type=${type}`, {
        method: 'POST',
        headers: token ? { Authorization: `Bearer ${token}` } : {},
        body: formData,
        credentials: 'include'
    });

    const data = await response.json();

    if (!response.ok) {
        return {
            error: data.detail || data.message || 'Error al subir el certificado',
            status: response.status
        };
    }

    return {
        data,
        status: response.status
    };
}
