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

export interface CanadianFraction {
    id: number;
    fraction: string;
    ad_valorem: number | null;
    unit_of_measure: string | null;
    country_code: string;
    description: string | null;
    created_at: string;
    updated_at: string;
}

export interface CanadianFractionList {
    items: CanadianFraction[];
    total: number;
    page: number;
    page_size: number;
    pages: number;
}

export interface CanadianFractionCreate {
    fraction: string;
    ad_valorem?: number;
    unit_of_measure?: string;
    country_code: string;
    description?: string;
}

export interface CanadianFractionUpdate {
    fraction?: string;
    ad_valorem?: number;
    unit_of_measure?: string;
    country_code?: string;
    description?: string;
}

const BASE_URL = '/v1/a76/fractions/canadian-tariff-fractions/';

export async function getCanadianFractions(
    companyId: number,
    page = 1,
    pageSize = 50,
    search?: string
): Promise<CanadianFractionList> {
    const params = new URLSearchParams({
        company_id: companyId.toString(),
        page: page.toString(),
        page_size: pageSize.toString()
    });

    if (search) params.append('search', search);

    const response = await api.get<CanadianFractionList>(`${BASE_URL}?${params.toString()}`);
    if (!response.data) throw new Error('Error fetching Canadian fractions');
    return response.data;
}

export async function createCanadianFraction(companyId: number, data: CanadianFractionCreate): Promise<CanadianFraction> {
    const params = new URLSearchParams({ company_id: companyId.toString() });
    const response = await api.post<CanadianFraction>(`${BASE_URL}?${params.toString()}`, data);
    if (!response.data) throw new Error('Error creating Canadian fraction');
    return response.data;
}

export async function updateCanadianFraction(companyId: number, id: number, data: CanadianFractionUpdate): Promise<CanadianFraction> {
    const params = new URLSearchParams({ company_id: companyId.toString() });
    const response = await api.put<CanadianFraction>(`${BASE_URL}${id}?${params.toString()}`, data);
    if (!response.data) throw new Error('Error updating Canadian fraction');
    return response.data;
}

export async function deleteCanadianFraction(companyId: number, id: number): Promise<void> {
    const params = new URLSearchParams({ company_id: companyId.toString() });
    await api.delete(`${BASE_URL}${id}?${params.toString()}`);
}
