/**
 * Week canonicalization (server side). **American style** — the week starts on
 * **Sunday**. Mirrors the frontend `shared/business/week.ts`; the F.R.A.M.E.
 * `week_of` is stored as the normalized Sunday-start ISO date.
 */

/**
 * Normalizes a `YYYY-MM-DD` date to its **Sunday** week-start ISO date.
 * Computed in UTC (calendar dates are timezone-agnostic). Returns `null` when
 * the input is not a valid `YYYY-MM-DD` date.
 */
export function toWeekStartIso(input: unknown): string | null {
  if (typeof input !== 'string') {
    return null;
  }
  const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(input.trim());
  if (!match) {
    return null;
  }

  const year = Number(match[1]);
  const month = Number(match[2]);
  const day = Number(match[3]);
  const date = new Date(Date.UTC(year, month - 1, day));

  // Reject overflow (e.g. 2026-02-31 rolls over).
  if (
    Number.isNaN(date.getTime()) ||
    date.getUTCFullYear() !== year ||
    date.getUTCMonth() !== month - 1 ||
    date.getUTCDate() !== day
  ) {
    return null;
  }

  date.setUTCDate(date.getUTCDate() - date.getUTCDay()); // back to Sunday
  return date.toISOString().slice(0, 10);
}
