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

export interface Package {
    id: number;
    tenant_id: number;
    company_id: number; 
    key: string;                     
    description_es: string | null;   
    description_en: string | null;   
    weight_unit: number | null;      
    plurals: string | null;          
    plural_in: string | null;        
    code_ace: string | null;         
    code_aamex: string | null;       
    created_at: string;
    updated_at?: string;
}

export interface PackageCreate {
    key: string;
    description_es?: string | null;
    description_en?: string | null;
    weight_unit?: number | null;
    plurals?: string | null;
    plural_in?: string | null;
    code_ace?: string | null;
    code_aamex?: string | null;
}

export interface PackageUpdate extends Partial<PackageCreate> {}

export interface PackageListResponse {
    items: Package[];
    total: number;
    page: number;
    page_size: number;
    pages: number;
}


export async function getPackages(
    page: number = 1,
    pageSize: number = 50,
    companyId: number, // Obligatorio por el Mixin
    filters: Record<string, any> = {}
): Promise<ApiResponse<PackageListResponse>> {
    const params = new URLSearchParams({
        page: page.toString(),
        page_size: pageSize.toString(),
        company_id: companyId.toString(),
        ...filters
    });

    return await api.get(`/v1/a76/packages/?${params.toString()}`);
}


export async function getPackage(id: number, companyId: number): Promise<ApiResponse<Package>> {
    return await api.get(`/v1/a76/packages/${id}?company_id=${companyId}`);
}

export async function createPackage(
    data: PackageCreate, 
    companyId: number
): Promise<ApiResponse<Package>> {
    return await api.post(`/v1/a76/packages/?company_id=${companyId}`, data);
}


export async function updatePackage(
    id: number, 
    data: PackageUpdate, 
    companyId: number
): Promise<ApiResponse<Package>> {
    return await api.put(`/v1/a76/packages/${id}/?company_id=${companyId}`, data);
}

export async function deletePackage(id: number, companyId: number): Promise<ApiResponse<void>> {
    return await api.delete(`/v1/a76/packages/${id}?company_id=${companyId}`);
}

// Wrapper object to match the rest of the codebase API style (e.g. `packagesApi.list(...)`)
export const packagesApi = {
    list: (companyId: number, options: Record<string, any> | undefined = {}) => {
        const { page = '1', page_size = '50', ...filters } = options as any;
        return getPackages(Number(page), Number(page_size), companyId, filters);
    },
    get: (id: number, companyId: number) => getPackage(id, companyId),
    create: (data: PackageCreate, companyId: number) => createPackage(data, companyId),
    update: (id: number, data: PackageUpdate, companyId: number) => updatePackage(id, data, companyId),
    delete: (id: number, companyId: number) => deletePackage(id, companyId)
};