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

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

export interface PrevalidatorCreate {
    code: string;
    description?: string;
    customs_prevalidator?: string;
    patent_prevalidator?: string;
}

export interface PrevalidatorUpdate extends Partial<PrevalidatorCreate> {}

export interface PrevalidatorListResponse {
    items: Prevalidator[];
    total: number;
    page: number;
    page_size: number;
    pages: number;
}

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

    const response = await api.get(`/v1/a76/prevalidators/?${params.toString()}`);
    return response.data;
}

export async function getPrevalidator(id: number, companyId?: number): Promise<Prevalidator> {
    const params = new URLSearchParams();
    if (companyId) {
        params.append('company_id', companyId.toString());
    }
    const response = await api.get(`/v1/a76/prevalidators/${id}?${params.toString()}`);
    return response.data;
}

export async function createPrevalidator(data: PrevalidatorCreate, companyId: number): Promise<Prevalidator> {
    const response = await api.post(`/v1/a76/prevalidators/?company_id=${companyId}`, data);
    return response.data;
}

export async function updatePrevalidator(id: number, data: PrevalidatorUpdate, companyId: number): Promise<Prevalidator> {
    const response = await api.put(`/v1/a76/prevalidators/${id}/?company_id=${companyId}`, data);
    return response.data;
}

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