import type { RevenueByCurrency } from "./types";

export const FX_RATES_SET_ON = "27 Oct 2026";

const USD_PER_UNIT: Record<string, number> = {
  USD: 1,
  INR: 1 / 90,
  EUR: 1.08,
  GBP: 1.27,
  AUD: 0.65,
  SGD: 0.74,
  IDR: 1 / 15800,
  THB: 1 / 36,
  VND: 1 / 25400,
};

export const CONVERTIBLE_CURRENCIES = Object.keys(USD_PER_UNIT);

export function toUsd(amount: number, currency: string | null | undefined) {
  const code = (currency ?? "USD").toUpperCase();
  const rate = USD_PER_UNIT[code];
  return {
    usd: amount * (rate ?? 1),
    converted: rate !== undefined,
    currency: code,
  };
}

export function revenueToUsd(revenue: RevenueByCurrency[] | undefined): {
  usd: number;
  unconverted: string[];
  nativeOnly: boolean;
} {
  let usd = 0;
  const unconverted: string[] = [];
  let nativeOnly = true;

  for (const row of revenue ?? []) {
    const result = toUsd(row.revenue, row.currency);
    usd += result.usd;
    if (!result.converted) unconverted.push(result.currency);
    else if (result.currency !== "USD") nativeOnly = false;
  }

  return { usd, unconverted, nativeOnly };
}

export function formatUsd(amount: number): string {
  return `$${amount.toLocaleString("en-US", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  })}`;
}

export function formatNativeBreakdown(
  revenue: RevenueByCurrency[] | undefined,
): string {
  if (!revenue?.length) return "No revenue recorded";
  const parts = revenue.map(
    (r) =>
      `${r.currency} ${r.revenue.toLocaleString("en-US", {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      })}`,
  );
  return `${parts.join(" + ")}`;
}
