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

export interface UnitConversion {
    id: number;
    from_unit_code: string; 
    to_unit_code: string;   
    conversion_factor: number;
    tenant_id: number;      // number
    company_id: number;     // number
    created_at: string;
    updated_at?: string;
}

export interface UnitConversionCreate {
    from_unit_code: string; // Ej: "KGM"
    to_unit_code: string;   // Ej: "LBR"
    conversion_factor: number;
    // company_id va en la URL
}

export interface UnitConversionUpdate extends Partial<UnitConversionCreate> {}

export interface UnitConversionListResponse {
    items: UnitConversion[];
    total: number;
    page: number;
    page_size: number;
    pages: number;
}


export async function getUnitConversions(
    page: number = 1,
    pageSize: number = 50,
    companyId: number, // 👈 Obligatorio
    filters: Record<string, any> = {}
): Promise<UnitConversionListResponse> {
    const params = new URLSearchParams({
        page: page.toString(),
        page_size: pageSize.toString(),
        company_id: companyId.toString(),
        ...filters
    });

    // Agregamos /v1 y prefijo. 
    // NOTA: Revisa si en tu router definiste "unit_conversions" o "unit-conversions"
    const response = await api.get<UnitConversionListResponse>(`/v1/a76/unit-conversions/?${params.toString()}`);
    if (response.error) throw new Error(response.error);
    if (!response.data) throw new Error('No se pudieron obtener las conversiones de unidades');
    return response.data;
}

export async function getUnitConversion(id: number, companyId: number): Promise<UnitConversion> {
    const response = await api.get<UnitConversion>(`/v1/a76/unit-conversions/${id}?company_id=${companyId}`);
    if (response.error) throw new Error(response.error);
    if (!response.data) throw new Error('No se pudo obtener la conversión de unidades');
    return response.data;
}

export async function createUnitConversion(
    data: UnitConversionCreate, 
    companyId: number
): Promise<UnitConversion> {
    const response = await api.post<UnitConversion>(`/v1/a76/unit-conversions/?company_id=${companyId}`, data);
    if (response.error) throw new Error(response.error);
    if (!response.data) throw new Error('No se pudo crear la conversión de unidades');
    return response.data;
}


export async function updateUnitConversion(
    id: number, 
    data: UnitConversionUpdate, 
    companyId: number
): Promise<UnitConversion> {
    const response = await api.put<UnitConversion>(`/v1/a76/unit-conversions/${id}/?company_id=${companyId}`, data);
    if (response.error) throw new Error(response.error);
    if (!response.data) throw new Error('No se pudo actualizar la conversión de unidades');
    return response.data;
}

export async function deleteUnitConversion(id: number, companyId: number): Promise<void> {
    // Backend DELETE route is defined without trailing slash: /unit-conversions/{id}
    const response = await api.delete(`/v1/a76/unit-conversions/${id}?company_id=${companyId}`);
    if (response.error) throw new Error(response.error);
}

export const unitConversionsApi = {
    list: (page = 1, pageSize = 50, companyId: number, filters: any = {}) => 
        getUnitConversions(page, pageSize, companyId, filters),
    get: (id: number, companyId: number) => 
        getUnitConversion(id, companyId),
    create: (data: UnitConversionCreate, companyId: number) => 
        createUnitConversion(data, companyId),
    update: (id: number, data: UnitConversionUpdate, companyId: number) => 
        updateUnitConversion(id, data, companyId),
    delete: (id: number, companyId: number) => 
        deleteUnitConversion(id, companyId)
};