// The one figure the item profitability report derives itself — Inventory
// Task 5.
//
// It lives in its own module rather than beside the component for the reason
// reports/inventoryValuationData.ts does: a file that exports both a React
// component and a plain function is not eligible for Fast Refresh, so every
// edit to the report full-reloads the page and drops whatever date range the
// developer had set. It is also the shape a unit test wants, and this one has
// a test (tests/web/inventory-report-text.test.ts).

/**
 * Margin as a percentage of revenue, to one decimal place — integer arithmetic
 * on the NUMERIC(19,4) digit strings, never a parsed float (CLAUDE.md §2 covers
 * anything derived from money, and a percentage of a money figure is exactly
 * that). Returns null when revenue is zero, where a percentage has no meaning.
 */
export function marginPercent(margin: string, revenue: string): string | null {
  const parse = (v: string): bigint | null => {
    const m = /^(-)?(\d+)\.(\d{4})$/.exec(v.trim());
    if (!m) return null;
    const magnitude = BigInt(m[2]! + m[3]!);
    return m[1] ? -magnitude : magnitude;
  };
  const num = parse(margin);
  const den = parse(revenue);
  if (num === null || den === null || den === 0n) return null;
  // *1000 so integer division leaves one decimal place, rounded half away from
  // zero. Sign is carried on the numerator only (revenue is never negative).
  const negative = num < 0n !== den < 0n;
  const scaled = (num < 0n ? -num : num) * 1000n;
  const d = den < 0n ? -den : den;
  const tenths = (scaled + d / 2n) / d;
  const whole = tenths / 10n;
  const frac = tenths % 10n;
  return `${negative && tenths !== 0n ? "-" : ""}${whole}.${frac}%`;
}
