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

export interface CustomsBrokerConcept {
    id: number;
    broker_key: string;
    concept: string;
    amount?: number | null;
    priority?: number | null;
    company_id: number;
    tenant_id: number;
    created_at: string;
    updated_at?: string | null;
}

export interface CustomsBrokerConceptCreate {
    broker_key: string;
    concept: string;
    amount?: number | null;
    priority?: number | null;
}

export interface CustomsBrokerConceptUpdate extends Partial<CustomsBrokerConceptCreate> {}

export interface CustomsBrokerConceptListResponse {
    items: CustomsBrokerConcept[];
    total: number;
    page: number;
    page_size: number;
    pages: number;
}

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

    return await api.get(`/v1/a76/customs-broker-concepts/?${params.toString()}`);
}

export async function getCustomsBrokerConcept(id: number, companyId: number): Promise<ApiResponse<CustomsBrokerConcept>> {
    return await api.get(`/v1/a76/customs-broker-concepts/${id}?company_id=${companyId}`);
}

export async function createCustomsBrokerConcept(data: CustomsBrokerConceptCreate, companyId: number): Promise<ApiResponse<CustomsBrokerConcept>> {
    return await api.post(`/v1/a76/customs-broker-concepts/?company_id=${companyId}`, data);
}

export async function updateCustomsBrokerConcept(id: number, data: CustomsBrokerConceptUpdate, companyId: number): Promise<ApiResponse<CustomsBrokerConcept>> {
    return await api.put(`/v1/a76/customs-broker-concepts/${id}/?company_id=${companyId}`, data);
}

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

export const customsBrokerConceptsApi = {
    list: (page = 1, pageSize = 50, companyId: number, filters: any = {}) => 
        getCustomsBrokerConcepts(page, pageSize, companyId, filters),
    get: (id: number, companyId: number) => 
        getCustomsBrokerConcept(id, companyId),
    create: (data: CustomsBrokerConceptCreate, companyId: number) => 
        createCustomsBrokerConcept(data, companyId),
    update: (id: number, data: CustomsBrokerConceptUpdate, companyId: number) => 
        updateCustomsBrokerConcept(id, data, companyId),
    delete: (id: number, companyId: number) => 
        deleteCustomsBrokerConcept(id, companyId)
};
