/**
 * IANA timezone validation + campus-local date helpers (zone check-in,
 * Workstream 16). A campus carries a required IANA `timezone`; "today" for a
 * user is computed server-side in that timezone so it is independent of the
 * caller's device clock/zone.
 */

// `Intl.supportedValuesOf` is available in Node 18+. Cache the set for O(1)
// validation.
const SUPPORTED_TIMEZONES: ReadonlySet<string> = new Set(
  Intl.supportedValuesOf('timeZone'),
);

export function isValidIanaTimezone(value: unknown): value is string {
  return typeof value === 'string' && SUPPORTED_TIMEZONES.has(value);
}

/**
 * The calendar date (YYYY-MM-DD) at `now` in the given IANA timezone. Uses the
 * native `Intl` formatter, so it is DST-correct with no extra dependency. The
 * `en-CA` locale yields an ISO-style `YYYY-MM-DD`.
 */
export function localDateInTimezone(timezone: string, now: Date = new Date()): string {
  return new Intl.DateTimeFormat('en-CA', {
    timeZone: timezone,
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  }).format(now);
}
