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

// Interfaces
export interface TariffFraction {
	id: number;
	code: string;
	fraction: string;
	description: string | null;
	nico: string | null;
	umt: string | null;
	adv_impo: string | null;
	adv_expo: string | null;
	updated_at: string | null;
	dof: string | null;
	aplica_ieps: string | null;
	um_code: string | null;
}

export interface TariffFractionCreate {
	code: string;
	fraction: string;
	description?: string | null;
	nico?: string | null;
	umt?: string | null;
	adv_impo?: string | null;
	adv_expo?: string | null;
}

export interface TariffFractionUpdate {
	fraction?: string;
	description?: string | null;
	nico?: string | null;
	umt?: string | null;
	adv_impo?: string | null;
	adv_expo?: string | null;
}

export interface TariffFractionListResponse {
	items: TariffFraction[];
	total: number;
	page: number;
	page_size: number;
	pages: number;
}

// API Functions
export async function getTariffFractions(
	page = 1,
	pageSize = 50,
	companyId: number,
	filters: Record<string, any> = {}
): Promise<ApiResponse<TariffFractionListResponse>> {
	const queryParams = new URLSearchParams({
		page: page.toString(),
		page_size: pageSize.toString(),
		company_id: companyId.toString(),
		...filters
	});
	return await api.get(`/v1/a76/tariff-fractions/?${queryParams.toString()}`);
}

export async function getTariffFractionById(
	id: number,
	companyId: number
): Promise<ApiResponse<TariffFraction>> {
	return await api.get(`/v1/a76/tariff-fractions/${id}/?company_id=${companyId}`);
}

export async function createTariffFraction(
	data: TariffFractionCreate,
	companyId: number,
	catalog = 'mex'
): Promise<ApiResponse<TariffFraction>> {
	return await api.post(
		`/v1/a76/tariff-fractions/?company_id=${companyId}&catalog=${catalog}`,
		data
	);
}

export async function updateTariffFraction(
	id: number,
	data: TariffFractionUpdate,
	companyId: number,
	catalog = 'mex'
): Promise<ApiResponse<TariffFraction>> {
	return await api.put(
		`/v1/a76/tariff-fractions/${id}/?company_id=${companyId}&catalog=${catalog}`,
		data
	);
}

export async function deleteTariffFraction(
	id: number,
	companyId: number,
	catalog = 'mex'
): Promise<ApiResponse<void>> {
	return await api.delete(
		`/v1/a76/tariff-fractions/${id}/?company_id=${companyId}&catalog=${catalog}`
	);
}
