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

export interface Legend {
    id: number;
    code: number;          
    description?: string;
    tenant_id: number;     
    company_id: number;     
    created_at: string;
    updated_at?: string;
}

export interface LegendCreate {
    code: number;         
    description?: string;
}

export interface LegendUpdate extends Partial<LegendCreate> {}

export interface LegendListResponse {
    items: Legend[];
    total: number;
    page: number;
    page_size: number;
    pages: number;
}

export async function getLegends(
    page: number = 1,
    pageSize: number = 50, 
    companyId: number, 
    filters: Record<string, any> = {}
): Promise<ApiResponse<LegendListResponse>> {
    const cleanFilters = Object.fromEntries(
        Object.entries(filters).filter(
            ([, v]) => v !== undefined && v !== null && v !== ''
        )
    );
    const params = new URLSearchParams({
        page: page.toString(),
        page_size: pageSize.toString(),
        company_id: companyId.toString(),
        ...cleanFilters
    });
    return await api.get(`/v1/a76/legends/?${params.toString()}`);
}

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

export async function createLegend(
    data: LegendCreate, 
    companyId: number
): Promise<ApiResponse<Legend>> {
    return await api.post(`/v1/a76/legends/?company_id=${companyId}`, data);
}

export async function updateLegend(
    id: number, 
    data: LegendUpdate, 
    companyId: number
): Promise<ApiResponse<Legend>> {
    return await api.put(`/v1/a76/legends/${id}/?company_id=${companyId}`, data);
}

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

// Wrapper object to match the rest of the codebase API style (e.g. `legendsApi.list(...)`)
export const legendsApi = {
    list: (companyId: number, options: Record<string, any> | undefined = {}) => {
        const { page = '1', page_size = '50', ...filters } = options as any;
        return getLegends(Number(page), Number(page_size), companyId, filters);
    },
    get: (id: number, companyId: number) => getLegend(id, companyId),
    create: (data: LegendCreate, companyId: number) => createLegend(data, companyId),
    update: (id: number, data: LegendUpdate, companyId: number) => updateLegend(id, data, companyId),
    delete: (id: number, companyId: number) => deleteLegend(id, companyId)
};