"use client";

import { useCurrency } from "@/lib/hooks/useCurrency";
import { FALLBACK_CURRENCY } from "@customer-portal/domain/billing";
import { formatCurrency as baseFormatCurrency } from "@customer-portal/domain/toolkit";

export type FormatCurrencyOptions = {
  currency?: string;
  currencySymbol?: string;
  locale?: string;
  showSymbol?: boolean;
};

const isOptions = (
  value: string | FormatCurrencyOptions | undefined
): value is FormatCurrencyOptions => {
  return typeof value === "object" && value !== null;
};

export function useFormatCurrency() {
  const { currencyCode, currencySymbol, loading, error } = useCurrency();

  const formatCurrency = (
    amount: number,
    currencyOrOptions?: string | FormatCurrencyOptions,
    options?: FormatCurrencyOptions
  ) => {
    const fallbackCurrency = currencyCode ?? FALLBACK_CURRENCY.code;
    const fallbackSymbol = currencySymbol ?? FALLBACK_CURRENCY.prefix;

    const overrideCurrency =
      (typeof currencyOrOptions === "string" && currencyOrOptions) ||
      (isOptions(currencyOrOptions) ? currencyOrOptions.currency : undefined) ||
      options?.currency;

    const overrideSymbol =
      (isOptions(currencyOrOptions) ? currencyOrOptions.currencySymbol : undefined) ||
      options?.currencySymbol;

    const locale =
      (isOptions(currencyOrOptions) ? currencyOrOptions.locale : undefined) || options?.locale;
    const showSymbol =
      (isOptions(currencyOrOptions) && typeof currencyOrOptions.showSymbol === "boolean"
        ? currencyOrOptions.showSymbol
        : undefined) ?? options?.showSymbol;

    return baseFormatCurrency(amount, overrideCurrency ?? fallbackCurrency, {
      currencySymbol: overrideSymbol ?? fallbackSymbol,
      locale,
      showSymbol,
    });
  };

  return {
    formatCurrency,
    currencyCode,
    loading,
    error,
  };
}
