/**
 * Destination-currency accounting (client 2026-11-05): customer bills are
 * kept in the destination's currency (Dubai → AED) whatever currency the
 * customer is billed in. The destination amount is the Markup panel's
 * "Total (AED)" BEFORE the selling price is rounded — e.g. AED 635.00
 * while the customer pays USD 173.00 (635 × 0.272972 = 173.34 → 173).
 * It is then rounded with the destination currency's own rounding step
 * (client 2026-11-07: AED 10,714.75 → 10,715 when AED rounds to 1).
 */

const round2 = (n: number) => Math.round(n * 100) / 100;

/** Round to a currency's step (1 → whole units); no step → 2 decimals. */
export function roundToStep(n: number, step?: number | null): number {
  const s = Number(step);
  if (!Number.isFinite(s) || s <= 0) return round2(n);
  return round2(Math.round(n / s) * s);
}

/**
 * The destination-currency total for a final selling price.
 *
 * - Same currency (or no destination currency) → the selling total itself.
 * - Otherwise the client-sent pre-rounding total is used when it agrees
 *   with the selling total within the rounding step (it can't be
 *   tampered into a different price); else selling ÷ rate.
 */
export function resolveDestinationTotal(input: {
  sellingTotal: number;
  sellingCurrencyId: string | null | undefined;
  destCurrencyId: string | null | undefined;
  exchangeRate: number;
  rounding?: number | null;
  clientDestTotal?: number | null;
  /** Destination currency's rounding step (AED = 1). */
  destRounding?: number | null;
}): number {
  const selling = Number(input.sellingTotal) || 0;
  if (!input.destCurrencyId || !input.sellingCurrencyId) return round2(selling);
  if (input.sellingCurrencyId === input.destCurrencyId) return round2(selling);
  const rate = Number(input.exchangeRate) > 0 ? Number(input.exchangeRate) : 1;
  const sent = input.clientDestTotal;
  if (sent !== null && sent !== undefined && Number.isFinite(Number(sent))) {
    const step = Math.max(0, Number(input.rounding) || 0);
    const tolerance = step / 2 + 0.02;
    if (Math.abs(Number(sent) * rate - selling) <= tolerance) {
      return roundToStep(Number(sent), input.destRounding);
    }
  }
  return roundToStep(selling / rate, input.destRounding);
}

/** A selling-currency amount in the destination currency (no rounding step). */
export function toDestinationAmount(
  sellingAmount: number,
  sellingCurrencyId: string | null | undefined,
  destCurrencyId: string | null | undefined,
  exchangeRate: number,
): number {
  if (!destCurrencyId || !sellingCurrencyId || sellingCurrencyId === destCurrencyId) {
    return round2(Number(sellingAmount) || 0);
  }
  const rate = Number(exchangeRate) > 0 ? Number(exchangeRate) : 1;
  return round2((Number(sellingAmount) || 0) / rate);
}

/** The destination's currency (raw SQL — tenant filtered explicitly). */
export async function destinationCurrencyId(
  manager: { query: (sql: string, params: unknown[]) => Promise<unknown> },
  tenantId: string,
  destinationId: string | null | undefined,
): Promise<string | null> {
  if (!destinationId) return null;
  const rows = (await manager.query(
    `SELECT currency_id FROM destinations WHERE id = $1 AND tenant_id = $2 LIMIT 1`,
    [destinationId, tenantId],
  )) as Array<{ currency_id: string | null }>;
  return rows[0]?.currency_id ?? null;
}

/** A currency's rounding step (raw SQL — tenant filtered explicitly). */
export async function currencyRounding(
  manager: { query: (sql: string, params: unknown[]) => Promise<unknown> },
  tenantId: string,
  currencyId: string | null | undefined,
): Promise<number | null> {
  if (!currencyId) return null;
  const rows = (await manager.query(
    `SELECT rounding FROM currencies WHERE id = $1 AND tenant_id = $2 LIMIT 1`,
    [currencyId, tenantId],
  )) as Array<{ rounding: string | number | null }>;
  const step = Number(rows[0]?.rounding);
  return Number.isFinite(step) && step > 0 ? step : null;
}
