/**
 * `GET /learn-serve-opportunities/{id}/registrations/` returns a **flat** row —
 * `user_name`, `user_email`, `user_id`, `civil_id` — with no nested `user`
 * object. Both register-list screens were written against an older nested
 * shape (`user.full_name`, `user.email`, `user.phone_number`), so every cell
 * read `undefined`: the table rendered names as blank and email/phone as "-",
 * and the certificate variant threw on `rowData.user.profile_pic` outright.
 *
 * Read a row through `registrationPerson()` instead of reaching into it, so
 * either shape renders. The flat payload gained
 * `full_name`, `user_contact_number` / `phone_number`, `profile_pic`,
 * `gender_display` and `is_public` on 2026-09-07 (BE-16 in
 * `docs/resolved/BACKEND_ISSUES_ROUND_1.md`), so all of them are read flat-first, then nested.
 */

interface NestedRegistrationUser {
  id?: number | string | null;
  full_name?: string | null;
  full_name_ar?: string | null;
  email?: string | null;
  phone_number?: string | null;
  profile_pic?: string | null;
  civil_id?: string | null;
  is_public?: boolean | null;
  gender_display?: { value_en?: string | null } | null;
  /**
   * The emergency-contact block. This is the **only** thing
   * `VolunteerOpportunityRegistrationResource`'s nested `user` actually
   * carries, besides `id` — not the display fields above, which that resource
   * does not send at all (BE-103).
   */
  emergency_contact_name?: string | null;
  emergency_contact_phone?: string | null;
  emergency_contact_civil_id?: string | null;
  emergency_contact_relationship_display?: {
    value_en?: string | null;
    value_ar?: string | null;
  } | null;
  /**
   * **Never sent** by either registration endpoint — that is BE-102. The
   * guardian columns read it, so it is declared to keep those reads honest
   * about what they are waiting for rather than silently absent.
   */
  dob?: string | null;
}

export interface RegistrationRow {
  can_exclude?: boolean;
  exclusion_closes_at?: string | null;
  /** Required: both resources always emit the registration's own id. */
  id: number | string;
  /** Flat shape (current). */
  user_id?: number | string | null;
  /**
   * `full_name` is the field both registration endpoints now agree on (added to
   * the learn-serve one on 2026-09-07, BE-16); `user_name` stays as its older
   * alias and is still sent.
   */
  full_name?: string | null;
  user_name?: string | null;
  user_email?: string | null;
  civil_id?: string | null;
  profile_pic?: string | null;
  gender_display?: { value_en?: string | null } | null;
  is_public?: boolean | null;
  /** Volunteer-registrations shape, still used by other endpoints. */
  user_full_name?: string | null;
  user_contact_number?: string | null;
  phone_number?: string | null;
  /** Nested shape (legacy, and the volunteer resource's emergency block). */
  user?: NestedRegistrationUser | null;
  /** Both resources send it; nullable on the learn & serve one. */
  is_attended?: boolean | null;
  /** A certificate was issued for this registration. */
  is_certified?: boolean | null;
  created_at?: string | null;
  registration_date?: string | null;
  /**
   * Development registrations only — `PaymentStatus` (BE-114). Null on a
   * free opportunity and on volunteering.
   */
  payment_status?: "pending" | "paid" | "refunded" | "failed" | "canceled" | null;
}

/**
 * Why the organizer may not remove this participant from a development
 * opportunity they paid for — the backend's rule
 * (`LearnServeRegistrationController::unregisterUser()`), confirmed as the
 * product rule on 2026-10-15:
 *
 * - `paid`    — they paid and were not refunded: refund first, then remove;
 * - `pending` — a checkout is open and could still complete. The API blocks
 *   only a checkout inside its 2-hour window, which the row cannot tell; the
 *   hourly expiry job moves a stale one off `pending`, and the API's 422 covers
 *   the gap in between.
 *
 * Refunded, failed or cancelled payments — and every row with no payment —
 * can be removed.
 */
export function paidRemovalBlock(
  row: RegistrationRow | null | undefined
): "paid" | "pending" | null {
  /* Keyed on the participant's own payment, not on whether the opportunity is
     paid *now*: switching it to free must not unlock the people who paid
     (BE-118). A free registration has no `payment_status`. */
  if (row?.payment_status === "paid") return "paid";
  if (row?.payment_status === "pending") return "pending";
  return null;
}

export interface RegistrationPerson {
  /** The registered user's own id — for the profile link. */
  userId?: number | string;
  name: string;
  nameAr: string;
  email: string;
  phone: string;
  civilId: string;
  profilePic: string;
  genderEn: string;
  /** Undefined when the payload doesn't say; callers route to the private profile. */
  isPublic?: boolean;
}

export function registrationPerson(
  row: RegistrationRow | null | undefined
): RegistrationPerson {
  const user = row?.user ?? undefined;
  const name =
    row?.full_name || row?.user_name || row?.user_full_name || user?.full_name || "";

  return {
    userId: user?.id ?? row?.user_id ?? undefined,
    name,
    // Only the nested shape ever carried an Arabic name; fall back to the one name we have.
    nameAr: user?.full_name_ar || name,
    email: row?.user_email || user?.email || "",
    phone: row?.user_contact_number || user?.phone_number || row?.phone_number || "",
    civilId: row?.civil_id || user?.civil_id || "",
    profilePic: row?.profile_pic || user?.profile_pic || "",
    genderEn: row?.gender_display?.value_en || user?.gender_display?.value_en || "",
    isPublic: row?.is_public ?? user?.is_public ?? undefined,
  };
}
