import { ageFromDateOfBirth } from "@/features/shared/dateOfBirth";
import { parseKuwaitInstant } from "@/features/shared/clientReviewPolicy";

/**
 * Age in whole years.
 *
 * The month/day adjustment is the only interesting part and it was written out
 * twice — once for "age at registration" on the opportunity registration lists
 * and once for "is this person underage" on the volunteer mandate form. Both
 * now call `ageAt`.
 *
 * Note what the adjustment is for: subtracting birth years alone is wrong for
 * anyone whose birthday has not come round yet in the reference year. Someone
 * born 2008-12-31, measured on 2026-06-01, is 17, not 18.
 */

/** The age reached by `at`, or `null` when either date is missing. */
export function ageAt(
  dob: string | null | undefined,
  at: string | Date | null | undefined
): number | null {
  if (!dob || !at) return null;

  const reference = at instanceof Date ? at : parseKuwaitInstant(at)?.toDate();
  return reference ? ageFromDateOfBirth(dob, reference) : null;
}

/** The age reached today. */
export const ageToday = (dob: string | null | undefined) =>
  ageFromDateOfBirth(dob);

/** Under 18 as of today. `false` when the date of birth is unknown. */
export const isUnderageToday = (dob: string | null | undefined) => {
  const age = ageToday(dob);
  return age !== null && age < 18;
};
