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

export interface INPC {
    id: number;
    year: string;
    month: string;
    value?: number;    
    tenant_id: number;  
    company_id: number; 
    created_at: string;
    updated_at?: string;
}

export interface INPCCreate {
    year: string;
    month: string;
    value?: number;
}

export interface INPCUpdate extends Partial<INPCCreate> {}

export interface INPCListResponse {
    items: INPC[];
    total: number;
    page: number;
    page_size: number;
    pages: number;
}

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

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

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

export async function createINPC(
    data: INPCCreate, 
    companyId: number
): Promise<ApiResponse<INPC>> {
    return await api.post(`/v1/a76/inpc/?company_id=${companyId}`, data);
}

export async function updateINPC(
    id: number, 
    data: INPCUpdate, 
    companyId: number
): Promise<ApiResponse<INPC>> {
    return await api.put(`/v1/a76/inpc/${id}/?company_id=${companyId}`, data);
}

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

export const inpcApi = {
    list: (companyId: number, options: Record<string, any> = {}) => {
        const { page = '1', page_size = '50', ...filters } = options;
        return getINPCs(Number(page), Number(page_size), companyId, filters);
    },
    get: (id: number, companyId: number) => getINPC(id, companyId),
    create: (data: INPCCreate, companyId: number) => createINPC(data, companyId),
    update: (id: number, data: INPCUpdate, companyId: number) => updateINPC(id, data, companyId),
    delete: (id: number, companyId: number) => deleteINPC(id, companyId)
};
