"use client";
import { useAuthStore } from "@/providers/AuthStoreProviders";
import { Currency } from "@/types/app_config";

interface FormatOptions {
  showSymbol?: boolean;
}

export const useCurrency = () => {
  const { appInfo } = useAuthStore((state: any) => state);

  // Get default currency from appInfo.application_info
  const defaultCurrency: Currency | undefined =
    appInfo?.application_info?.defaultCurrency;

  // fallback if API not loaded
  const currency: Currency = defaultCurrency || {
    name: "US Dollar",
    code: "USD",
    symbol: "$",
    symbol_position: "left",
    thousand_separator: ",",
    decimal_separator: ".",
    precision: 2,
    rate: "1",
    status: "active",
    is_default: true,
  };

  const format = (value: number, options?: FormatOptions) => {
    const showSymbol = options?.showSymbol ?? true;

    const parts = value.toFixed(currency.precision).split(".");
    parts[0] = parts[0].replace(
      /\B(?=(\d{3})+(?!\d))/g,
      currency.thousand_separator,
    );
    const formattedNumber = parts.join(currency.decimal_separator);

    if (!showSymbol) return formattedNumber;

    return currency.symbol_position === "left"
      ? `${currency.symbol}${formattedNumber}`
      : `${formattedNumber}${currency.symbol}`;
  };

  return { currency, format };
};
