/**
 * Whether a registration row should show its emergency-contact columns.
 *
 * These columns exist for one reason: a volunteer who was **under 18 when they
 * registered** has a guardian's details on file, and the organizer needs them.
 * The age is measured at the registration date, not today — someone who
 * registered at 17 and has since turned 18 still registered as a minor, and
 * their guardian is still who the organizer would call.
 *
 * Pure, and out of the table component, because that "at registration" detail
 * is the whole rule and was previously buried in a 935-line screen where it
 * could not be asserted. Two registration lists apply it.
 */

import { ageAt } from "@/lib/age";

/** The fields the rule reads off a registration row. */
export interface EmergencyContactSource {
  created_at?: string | null;
  registration_date?: string | null;
  user?: {
    dob?: string | null;
    /**
     * The server's own answer (`User::isMinor(18, registration_date)`), sent
     * by both registration resources. It also covers a minor stored with a
     * birth year only, whom the `dob` arithmetic below cannot see.
     */
    show_guardian_contact?: boolean | null;
    emergency_contact_name?: string | null;
    emergency_contact_phone?: string | null;
    emergency_contact_civil_id?: string | null;
    emergency_contact_relationship_display?: unknown;
  } | null;
}

/** The age the person had reached on `registrationDate`, or null if unknowable. */
export function calculateAgeAtRegistration(
  dob: string | null | undefined,
  registrationDate: string | null | undefined
): number | null {
  // The month/day adjustment lives in `lib/age.ts`; it was duplicated here and
  // in the volunteer mandate form.
  return ageAt(dob, registrationDate);
}

/**
 * True only for a minor at registration who actually has contact details
 * stored. Without the second half the columns appear full of dashes for every
 * under-18 registration that predates the guardian fields.
 */
export function shouldShowEmergencyContact(
  rowData: EmergencyContactSource | null | undefined
): boolean {
  const serverFlag = rowData?.user?.show_guardian_contact;
  if (serverFlag === false) return false;
  if (serverFlag !== true) {
    // Older payloads without the flag: derive it from the dates.
    const dob = rowData?.user?.dob;
    const createdAt = rowData?.created_at || rowData?.registration_date;
    if (!dob || !createdAt) return false;
    const age = calculateAgeAtRegistration(dob, createdAt);
    if (age === null || age >= 18) return false;
  }

  const hasEmergencyContact =
    rowData?.user?.emergency_contact_name ||
    rowData?.user?.emergency_contact_phone ||
    rowData?.user?.emergency_contact_civil_id ||
    rowData?.user?.emergency_contact_relationship_display;

  return !!hasEmergencyContact;
}
