
import { formatCurrency as formatCurrencyUtil } from './currency-formatter';

const DEFAULT_CURRENCY_SYMBOL = String(process.env.NEXT_PUBLIC_DEFAULT_CURRENCY_SYMBOL || '$').trim() || '$';

/**
 * Server-side utility to get the default currency symbol
 * This function can only be used in Server Components
 * @returns The currency symbol or '$' as fallback
 */
export function getCurrencySymbol(): string {
  return DEFAULT_CURRENCY_SYMBOL;
}

export async function getCurrencySymbolAsync(): Promise<string> {
  try {
    
    const { pgGetDefaultCurrency } = await import('@/lib/postgres/data-access');
    return String((await pgGetDefaultCurrency())?.symbol || DEFAULT_CURRENCY_SYMBOL).trim() || DEFAULT_CURRENCY_SYMBOL;
  } catch {
    return DEFAULT_CURRENCY_SYMBOL;
  }
}

/**
 * Server-side utility to format amount without currency symbol
 * This function can only be used in Server Components
 * @param amount - The numeric amount to format
 * @param decimalPlaces - Number of decimal places (default: 2)
 * @returns Formatted string without currency symbol
 */
export function formatCurrency(amount: number, decimalPlaces: number = 2): string {
  const symbol = getCurrencySymbol();
  return formatCurrencyUtil(amount, symbol, decimalPlaces);
}

/**
 * Async version of formatCurrency – reads the default currency symbol from the database.
 * Use this in async Server Components for the most up-to-date symbol.
 */
export async function formatCurrencyAsync(amount: number, decimalPlaces: number = 2): Promise<string> {
  const symbol = await getCurrencySymbolAsync();
  return formatCurrencyUtil(amount, symbol, decimalPlaces);
}
