/**
 * API para gestión de Fixed Asset Classes (Clases de Activos Fijos A24)
 */
import { api } from '$lib/api';
import type { ApiResponse } from '$lib/api';

export interface FAClass {
	id: number;
	tenant_id: number;
	company_id: number;
	class_id: number;
	import_tariff_code: string | null;
	import_tariff_type: string | null;
	export_tariff_code: string | null;
	export_tariff_type: string | null;
	depreciation_rate: number | null;
	fda_code: string | null;
	eccn_code: string | null;
	class_enabled: boolean | null;
	created_at: string;
	updated_at: string;
}

export interface FAClassCreate {
	class_id: number;
	import_tariff_code?: string | null;
	import_tariff_type?: string | null;
	export_tariff_code?: string | null;
	export_tariff_type?: string | null;
	depreciation_rate?: number | null;
	fda_code?: string | null;
	eccn_code?: string | null;
	class_enabled?: boolean;
}

export interface FAClassUpdate {
	import_tariff_code?: string | null;
	import_tariff_type?: string | null;
	export_tariff_code?: string | null;
	export_tariff_type?: string | null;
	depreciation_rate?: number | null;
	fda_code?: string | null;
	eccn_code?: string | null;
	class_enabled?: boolean;
}

export interface FAClassListResponse {
	items: FAClass[];
	total: number;
	page: number;
	page_size: number;
}

export interface FAClassListParams {
	company_id: number;
	page?: number;
	page_size?: number;
	class_id?: number;
	fda_code?: string;
	class_enabled?: boolean;
}

/**
 * API de Fixed Asset Classes
 */
export const faClassesApi = {
	/**
	 * Obtener lista de clases de activos fijos con paginación
	 */
	list: (params: FAClassListParams): Promise<ApiResponse<FAClassListResponse>> => {
		const { company_id, page = 1, page_size = 50, ...filters } = params;
		const queryParams = new URLSearchParams({
			company_id: company_id.toString(),
			page: page.toString(),
			page_size: page_size.toString(),
			...Object.fromEntries(
				Object.entries(filters).filter(([_, v]) => v !== undefined).map(([k, v]) => [k, String(v)])
			)
		});
		return api.get(`/v1/a24/fa/classes/?${queryParams}`);
	},

	/**
	 * Obtener una clase de activo fijo por ID
	 */
	get: (id: number, company_id: number): Promise<ApiResponse<FAClass>> => {
		return api.get(`/v1/a24/fa/classes/${id}?company_id=${company_id}`);
	},

	/**
	 * Crear una nueva clase de activo fijo
	 */
	create: (data: FAClassCreate, company_id: number): Promise<ApiResponse<FAClass>> => {
		return api.post(`/v1/a24/fa/classes/?company_id=${company_id}`, data);
	},

	/**
	 * Actualizar una clase de activo fijo existente
	 */
	update: (id: number, data: FAClassUpdate, company_id: number): Promise<ApiResponse<FAClass>> => {
		return api.put(`/v1/a24/fa/classes/${id}/?company_id=${company_id}`, data);
	},

	/**
	 * Eliminar una clase de activo fijo
	 */
	delete: (id: number, company_id: number): Promise<ApiResponse<void>> => {
		return api.delete(`/v1/a24/fa/classes/${id}?company_id=${company_id}`);
	}
};
