"use client";

import { useQuery } from "@tanstack/react-query";
import { queryKeys } from "@/lib/api";
import { currencyService } from "@/lib/services/currency.service";
import { FALLBACK_CURRENCY, type WhmcsCurrency } from "@customer-portal/domain/billing";

export function useCurrency() {
  const { data, isLoading, isError, error } = useQuery<WhmcsCurrency>({
    queryKey: queryKeys.currency.default(),
    queryFn: () => currencyService.getDefaultCurrency(),
    staleTime: 60 * 60 * 1000, // cache currency for 1 hour
    gcTime: 2 * 60 * 60 * 1000,
    retry: 2,
  });

  const resolvedCurrency = data ?? (isError ? FALLBACK_CURRENCY : null);
  const currencyCode = resolvedCurrency?.code ?? FALLBACK_CURRENCY.code;
  const currencySymbol = resolvedCurrency?.prefix ?? FALLBACK_CURRENCY.prefix;

  return {
    currency: resolvedCurrency,
    loading: isLoading,
    error: isError ? (error instanceof Error ? error.message : "Failed to load currency") : null,
    currencyCode,
    currencySymbol,
  };
}
