/**
 * API Client para Exchange Rate
 */
import { api } from '$lib/api';

export interface ExchangeRate {
	id: number;
	date: string;
	value: number;
	local_currency: string | null;
	foreign_currency: string | null;
	company_id: number;
	tenant_id: number;
}

export interface ExchangeRateListResponse {
	items: ExchangeRate[];
	total: number;
	page: number;
	size: number;
	pages: number;
}

/**
 * Get exchange rate by date
 */
export async function getExchangeRateByDate(date: string, companyId: number): Promise<ExchangeRate | null> {
	try {		
		const dateOnly = date.split('T')[0]; // Ensure YYYY-MM-DD
		// Filter by date on server side
		const response = await api.get<ExchangeRateListResponse>(`/v1/a76/exchange-rate/?company_id=${companyId}&date=${dateOnly}`);		
		
		if (response.data && response.data.items && response.data.items.length > 0) {
			// Find USD exchange rate (backend might return multiple currencies for same date if they exist)									
			return response.data.items[0];
		}
				
		return null;
	} catch (error) {
		console.error('❌ [API] Error fetching exchange rate:', error);
		return null;
	}
}
