/**
 * API Client para Unit Measures - Catálogo principal de unidades de medida
 */
import { api } from '$lib/api';
import type { ApiResponse } from '$lib/api';

export interface UnitMeasure {
    id: number;
    code: string;
    description: string | null;
    created_at: string | null;
    updated_at: string | null;
}

export interface UnitMeasureCreate {
    code: string;
    description?: string | null;
}

export interface UnitMeasureUpdate {
    code?: string;
    description?: string | null;
}

export interface UnitMeasureListResponse {
    items: UnitMeasure[];
    total: number;
    page: number;
    page_size: number;
    pages: number;
}

/**
 * Lista todas las unidades de medida
 */
export async function getUnitMeasures(
    page = 1,
    pageSize = 50,
    filters: Record<string, any> = {}
): Promise<ApiResponse<UnitMeasureListResponse>> {
    const queryParams = new URLSearchParams({
        page: page.toString(),
        page_size: pageSize.toString(),
        ...filters
    });
    return await api.get(`/a76/units-of-measure/?${queryParams.toString()}`);
}

/**
 * Obtiene una unidad de medida por ID
 */
export async function getUnitMeasure(id: number): Promise<ApiResponse<UnitMeasure>> {
    return await api.get(`/a76/units-of-measure/${id}`);
}

/**
 * Crea una nueva unidad de medida
 */
export async function createUnitMeasure(data: UnitMeasureCreate): Promise<ApiResponse<UnitMeasure>> {
    return await api.post('/a76/units-of-measure/', data);
}

/**
 * Actualiza una unidad de medida
 */
export async function updateUnitMeasure(id: number, data: UnitMeasureUpdate): Promise<ApiResponse<UnitMeasure>> {
    return await api.put(`/a76/units-of-measure/${id}/`, data);
}

/**
 * Elimina una unidad de medida
 */
export async function deleteUnitMeasure(id: number): Promise<ApiResponse<void>> {
    return await api.delete(`/a76/units-of-measure/${id}/`);
}
