import { HttpError } from "./errors";

export function formatAmount(input: number | string): string {
  if (typeof input === "number") {
    if (!Number.isFinite(input) || input <= 0) {
      throw new HttpError(400, "Amount must be greater than zero");
    }
    const cents = Math.round(input * 100);
    if (Math.abs(cents / 100 - input) > 1e-8) {
      throw new HttpError(400, "Amount must have at most 2 decimal places");
    }
    const formatted = (cents / 100).toFixed(2);
    if (formatted.length > 10) {
      throw new HttpError(400, "Amount is longer than iPay allows (10 characters)");
    }
    return formatted;
  }

  const raw = input.trim();
  if (!/^(0|[1-9]\d*)(\.\d{1,2})?$/.test(raw)) {
    throw new HttpError(400, "Amount must be a positive number with up to 2 decimal places");
  }
  const numeric = Number(raw);
  if (!(numeric > 0)) {
    throw new HttpError(400, "Amount must be greater than zero");
  }
  const [whole, fraction = ""] = raw.split(".");
  const formatted = `${whole}.${fraction.padEnd(2, "0")}`;
  if (formatted.length > 10) {
    throw new HttpError(400, "Amount is longer than iPay allows (10 characters)");
  }
  return formatted;
}

export function amountsEqual(stored: string, received: string): boolean {
  const left = Number(stored);
  const right = Number(String(received).replace(/,/g, ""));
  if (!Number.isFinite(left) || !Number.isFinite(right)) return false;
  return Math.round(left * 100) === Math.round(right * 100);
}
