"use client";

import { useQuery } from "@tanstack/react-query";
import { queryKeys } from "@/core/api";
import { currencyService } from "@/shared/api";
import { FALLBACK_CURRENCY, type Currency } from "@customer-portal/domain/billing";

export function useCurrency() {
  const { data, isLoading, isError, error } = useQuery<Currency>({
    queryKey: queryKeys.currency.default(),
    queryFn: () => currencyService.getDefaultCurrency(),
    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,
  };
}
