import { api } from '$lib/api';
import type { ApiResponse } 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<ApiResponse<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(`/v1/a76/unit-conversions/?${params.toString()}`);
    return response.data;
}

export async function getUnitConversion(id: number, companyId: number): Promise<UnitConversion> {
    const response = await api.get(`/v1/a76/unit-conversions/${id}/?company_id=${companyId}`);
    if (response.error) throw new Error(response.error);
    return response.data;
}

export async function createUnitConversion(
    data: UnitConversionCreate, 
    companyId: number
): Promise<UnitConversion> {
    const response = await api.post(`/v1/a76/unit-conversions/?company_id=${companyId}`, data);
    if (response.error) throw new Error(response.error);
    return response.data;
}


export async function updateUnitConversion(
    id: number, 
    data: UnitConversionUpdate, 
    companyId: number
): Promise<UnitConversion> {
    const response = await api.put(`/v1/a76/unit-conversions/${id}/?company_id=${companyId}`, data);
    if (response.error) throw new Error(response.error);
    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);
}