/**
 * API Client para Items
 * Gestiona las operaciones CRUD para items de facturas
 */
import { api } from '$lib/api';

// --- Interfaces ---

// --- Nested Interfaces for Line Items ---

export interface LineCustoms {
    id?: number;
    line_item_id?: number;
    fraction?: string;
    fraction_type?: string;
    american_fraction?: string;
    origin_country?: string;
    destination_country?: string;
    advalorem?: string;
    advalorem_numeric?: number;
    advalorem_american?: number;
    advalorem_tlcan?: number;
    rate?: string;
    depreciation_rate?: number;
    sector?: string;
}

export interface LineFinancials {
    id?: number;
    line_item_id?: number;
    // Costs
    unit_cost_usd?: number;
    unit_cost_mxn?: number;
    unit_cost_capture?: number;
    unit_cost_commercial_usd?: number;
    unit_cost_mc?: number;

    // Values
    value_mc?: number;
    value_usd?: number;
    value_mxn?: number;
    value_returned_usd?: number;
    value_returned_mxn?: number;
    customs_value_usd?: number;
    customs_value_mxn?: number;
    vat_mxn?: number;
    vat_usd?: number;
    vat_mc?: number;
}

export interface LineQuantities {
    id?: number;
    line_item_id?: number;
    quantity?: number;
    unit_of_measure?: string;

    // Special quantities
    quantity_temp_export?: number;

    // Weight
    net_weight?: number;
    gross_weight?: number;

    // Packaging
    package_id?: number; // Changed from string to number - this is the ID from packages catalog
    package_quantity?: number;
    package_description?: string; // This is for display purposes only
}

export interface LineDescriptions {
    id?: number;
    line_item_id?: number;
    description_spanish?: string;
    description_english?: string;
    extra_description?: string;
    additional_info_spanish?: string;
    brand?: string;
    model?: string;
    has_serial?: boolean;
    lot?: string;
    entry_number?: string;
    eighth_rule_fraction?: string;
    eighth_rule_line?: number;
    consider_a31?: boolean;
    machinery_location?: string;
}

export interface LineReferences {
    id?: number;
    line_item_id?: number;
    serie_id?: number;
}

import type { 
    IdentifierDetail 
} from './general_catalogs/identifiers';

export interface Serie {
    id?: number;
    line_item_id?: number;
    row?: number;
    serial_numbers?: string;
    model?: string;
    sub_model?: string;
    brand?: string;
    expo_brad?: string;
    number_id?: string;
    import_invoice?: string;
    import_line?: number;
    image_path?: string;
}

export interface FaLineItem {
    id?: number;
    tenant_id?: number;
    company_id?: number;

    // Asset information (SCAF specific)
    asset_number?: string;
    asset_photo?: string;
    equipment_message?: string;
    invoice_type_asset?: string;
    return_import_invoice?: string;
    return_import_date?: number;
    movement_type_import?: string;

    // Cross-references for import repair
    search_invoice?: string;
    search_line?: number;

    // Search type
    search_type?: string;

    // Subitems
    is_subitem?: boolean;
    contains_subitems?: boolean;
    subitem_number?: number;

    // Special flags
    discharge?: boolean;
    own_equipment?: boolean;
    omit_annex31?: boolean;

    // Source data for proportional calculations (CALCULO_PESOS) and inventory balance validation
    source_quantity?: number;
    source_balance?: number;
    source_net_weight?: number;
    source_gross_weight?: number;
    source_packages?: number;

    // Timestamps
    created_at?: string;
    updated_at?: string;
}

export interface Item {
    id?: number;
    invoice_id: number;
    line_number: number;

    // Identification
    part_number?: string;
    part_number_id?: number;
    component_part_number?: string;
    component_part_number_id?: number;
    class_id?: number;
    identifier?: string;

    // Unit of Measure
    unit_of_measure?: number;
    alternate_unit?: number;

    // Permits
    permit_number?: string;
    page_line?: string;
    has_fda_code?: boolean;
    fda_key?: string;
    fcc_key?: string;
    has_certificate?: boolean;
    certificate_number?: string;
    certificate_end_date?: string;
    octave_permit?: string;

    // Flags
    is_subitem?: boolean;
    includes_subitems?: boolean;
    tax_payment?: boolean;
    is_military_mcia?: boolean;

    // Payment
    payment_method?: string;
    igi_payment_method?: string;
    igi_amount?: number;

    // Export valuation (Met Valor, Valor Det., Motivo De Uso)
    valuation_method?: string;
    valuation_determined_value?: number;
    valuation_reason?: string;

    // Additional notes
    wildcard_field?: string;

    // Computed fields from class_info relation
    class_code?: string;
    class_description?: string;

    // Computed field from unit_of_measure_info relation
    unit_of_measure_code?: string;
    reference_number?: string;
    order?: string;
    guide_number?: string;
    depreciation_date?: string;
    rectification?: number;
    warehouse?: string;
    location?: string;
    created_at?: string;
    updated_at?: string;

    // Nested relations (Singular names to match backend Pydantic models)
    customs?: LineCustoms;
    financial?: LineFinancials;
    quantity?: LineQuantities;
    description?: LineDescriptions;
    reference?: LineReferences;
    fa_data?: FaLineItem; // Fixed Asset specific data
    series?: Serie[]; // Series data (multiple per line)
    identifiers?: IdentifierDetail[]; // Identifiers for this line
}

export interface ItemListResponse {
    items: Item[];
    total: number;
    skip: number;
    limit: number;
}

export interface CreateItemData extends Omit<Item, 'id' | 'created_at' | 'updated_at'> {
    invoice_id: number;
}

export interface UpdateItemData extends Partial<Omit<Item, 'id' | 'invoice_id' | 'created_at' | 'updated_at'>> { }

/**
 * API para Items
 */
export const itemsApi = {
    /**
     * Lista todos los items con paginación
     */
    list: (companyId: number, skip = 0, limit = 100, invoiceId?: number) => {
        const params = new URLSearchParams({
            company_id: companyId.toString(),
            skip: skip.toString(),
            limit: limit.toString()
        });

        if (invoiceId) {
            params.append('invoice_id', invoiceId.toString());
        }

        return api.get<ItemListResponse>(`/v1/a76/items/?${params.toString()}`);
    },

    /**
     * Lista items por invoice ID
     */
    listByInvoice: (invoiceId: number, companyId: number) => {
        const params = new URLSearchParams({
            company_id: companyId.toString()
        });
        return api.get<ItemListResponse>(`/v1/a76/items/invoice/${invoiceId}/items/?${params.toString()}`);
    },

    /**
     * Obtiene un item por ID
     */
    get: (itemId: number, companyId: number) => {
        const params = new URLSearchParams({
            company_id: companyId.toString()
        });
        return api.get<Item>(`/v1/a76/items/${itemId}/?${params.toString()}`);
    },

    /**
     * Crea un nuevo item
     */
    create: (companyId: number, data: CreateItemData) => {
        const params = new URLSearchParams({
            company_id: companyId.toString()
        });
        return api.post<Item>(`/v1/a76/items/?${params.toString()}`, data);
    },

    /**
     * Actualiza un item existente
     */
    update: (itemId: number, companyId: number, data: UpdateItemData) => {
        const params = new URLSearchParams({
            company_id: companyId.toString()
        });
        return api.put<Item>(`/v1/a76/items/${itemId}/?${params.toString()}`, data);
    },

    delete: (itemId: number, companyId: number) => {
        const params = new URLSearchParams({
            company_id: companyId.toString()
        });
        return api.delete(`/v1/a76/items/${itemId}/?${params.toString()}`);
    },

    /**
     * Elimina todas las series de un item
     */
    deleteSeries: (itemId: number, companyId: number) => {
        const params = new URLSearchParams({
            company_id: companyId.toString()
        });
        return api.delete<{ message: string; count: number }>(
            `/v1/a76/items/${itemId}/series?${params.toString()}`
        );
    },

    /**
     * Lista las líneas de una factura de importación con su saldo disponible.
     * Solo las líneas con has_balance = true tienen mercancía disponible para descarga.
     *
     * @param invoiceId  - ID de la factura de importación
     * @param companyId  - ID de la empresa
     * @param asOfDate   - Fecha corte opcional (ISO: "YYYY-MM-DD").
     *                     Pasa la fecha de la factura de exportación para que
     *                     los consumos futuros no se descuenten del saldo.
     */
    listByInvoiceWithBalance: (
        invoiceId: number,
        companyId: number,
        asOfDate?: string,
        currentExportInvoiceId?: number
    ) => {
        const params = new URLSearchParams({ company_id: companyId.toString() });
        if (asOfDate) params.append('as_of_date', asOfDate);
        if (currentExportInvoiceId) params.append('current_export_invoice_id', currentExportInvoiceId.toString());
        return api.get<ImportLineWithBalance[]>(
            `/v1/a76/items/invoice/${invoiceId}/items-with-balance?${params.toString()}`
        );
    }
};

export interface ImportLineWithBalance {
    id: number;
    line_number: number;
    // Invoice info
    invoice_number?: string;
    invoice_date?: string;
    invoice_status?: string;
    // Part / class
    part_number?: string;
    class_code?: string;
    description_spanish?: string;
    unit_of_measure_code?: string;
    // Quantities
    quantity?: number;
    quantity_used_temp?: number;
    quantity_used_def?: number;
    // Weights
    net_weight?: number;
    gross_weight?: number;
    // Balance
    available_balance: number;
    has_balance: boolean;
    // FA / subitem
    is_subitem?: boolean;
    contains_subitems?: boolean;
    subitem_count?: number;
}
