import { useQuery } from "@tanstack/react-query";
import { apiGet } from "../lib/api";

interface ExchangeRates {
	base: string;
	date: string;
	rates: Record<string, number>;
}

export function useExchangeRates() {
	return useQuery({
		queryKey: ["exchange-rates"],
		queryFn: () => apiGet<ExchangeRates>("/api/exchange-rates"),
		staleTime: 1000 * 60 * 60, // 1 hour client-side stale time
		gcTime: 1000 * 60 * 60 * 24, // 24 hour garbage collection
		refetchOnWindowFocus: false,
	});
}

/**
 * Convert price in cents from one currency to another using provided rates.
 * All conversions go through EUR as the base currency.
 */
export function convertClientPrice(
	cents: number,
	from: string,
	to: string,
	rates: Record<string, number>,
): number {
	if (from === to) return cents;
	const fromRate = rates[from] ?? 1;
	const toRate = rates[to] ?? 1;
	return Math.round((cents / fromRate) * toRate);
}
