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

// --- INTERFACES ---

export interface A76Class {
    id: number;
    tenant_id: number;
    company_id: number;
    class_code: string;
    description_es: string | null;
    description_en: string | null;
    material_key: string | null;
    unit_of_measure: string;
    fraction: string;
    us_fraction: string;
    sub_key: string;
    physical_review: number;
    iva_exempt_fraction: string;
    eccn_code?: string | null;
    is_active?: boolean; // Agregado para el switch del formulario
    created_at: string;
    updated_at: string;
}

// DTO para crear (match con tu formulario)
export interface A76ClassCreate {
    company_id: number;
    class_code: string;
    description_es?: string | null;
    description_en?: string | null;
    material_key?: string | null;
    unit_of_measure?: string | null;
    fraction?: string | null;
    us_fraction?: string | null;
    sub_key?: string | null;
    physical_review?: number | null;
    iva_exempt_fraction?: string | null;
    eccn_code?: string | null;
    is_active?: boolean;
}

// DTO para actualizar (Partial del create)
export interface A76ClassUpdate extends Partial<A76ClassCreate> { }

export interface A76ClassListResponse {
    items: A76Class[];
    classes?: A76Class[];
    total: number;
    page: number;
    page_size: number;
    size?: number;
}

/** Respuesta de GET /v1/a76/classes/with-fa-data */
export interface A76ClassWithFADataPageResponse {
    items: A76Class[];
    total: number;
    page: number;
    page_size: number;
}

export interface A76ClassListParams {
    company_id: number;
    page?: number;
    page_size?: number;
    class_code?: string;
    description?: string;
    /** Búsqueda OR en class_code, description_es y description_en (backend ClassService) */
    search?: string;
    q?: string;
    sort_by?: string;
    sort_order?: 'asc' | 'desc';
}

// --- API OBJECT ---

export const classesApi = {
    list: (params: A76ClassListParams): Promise<ApiResponse<A76ClassListResponse>> => {
        const query = new URLSearchParams();
        Object.entries(params).forEach(([key, value]) => {
            if (value !== undefined && value !== null) query.append(key, value.toString());
        });
        return api.get(`/v1/a76/classes/?${query.toString()}`);
    },

    get: (id: number, company_id: number): Promise<ApiResponse<A76Class>> => {
        return api.get(`/v1/a76/classes/${id}?company_id=${company_id}`);
    },

    create: (data: A76ClassCreate, company_id: number): Promise<ApiResponse<A76Class>> => {
        return api.post(`/v1/a76/classes/?company_id=${company_id}`, data);
    },

    update: (id: number, data: A76ClassUpdate, company_id: number): Promise<ApiResponse<A76Class>> => {
        return api.put(`/v1/a76/classes/${id}/?company_id=${company_id}`, data);
    },

    /**
     * Eliminar un class
     */
    delete: (id: number, company_id: number): Promise<ApiResponse<void>> => {
        return api.delete(`/v1/a76/classes/${id}?company_id=${company_id}`);
    },

    /**
     * Inicializar datos semilla de clases de activo fijo
     */
    seed: (company_id: number): Promise<ApiResponse<{ message: string; count: number }>> => {
        return api.post(`/v1/a76/classes/seed?company_id=${company_id}`, {});
    },

    /**
     * Crear una clase de activo fijo (crea tanto A76Class como FAClass en una transacción)
     */
    createFA: (data: any, company_id: number): Promise<ApiResponse<any>> => {
        return api.post(`/v1/a76/classes/fa?company_id=${company_id}`, data);
    },

    /**
     * Clases con datos FA (JOIN); respuesta paginada desde el servidor.
     */
    getWithFAData: (params: {
        company_id: number;
        page?: number;
        page_size?: number;
        sort_by?: string;
        sort_order?: 'asc' | 'desc';
        class_code?: string;
        description?: string;
        material_key?: string;
        fraction?: string;
    }): Promise<ApiResponse<A76ClassWithFADataPageResponse>> => {
        const query = new URLSearchParams({
            company_id: params.company_id.toString(),
            page: (params.page || 1).toString(),
            page_size: (params.page_size || 50).toString()
        });

        if (params.sort_by) query.append('sort_by', params.sort_by);
        if (params.sort_order) query.append('sort_order', params.sort_order);
        if (params.class_code) query.append('class_code', params.class_code);
        if (params.description) query.append('description', params.description);
        if (params.material_key) query.append('material_key', params.material_key);
        if (params.fraction) query.append('fraction', params.fraction);
        return api.get(`/v1/a76/classes/with-fa-data?${query.toString()}`);
    }
};