/**
 * One row of the organizer's volunteer picker.
 *
 * Transcribed from `App\Http\Resources\Volunteer\VolunteerPickerResource`,
 * which serves both `GET /all-volunteers/` and `GET /available-volunteers/`.
 *
 * BE-82 deliberately narrowed this payload: identifiers come back as their
 * last four characters only — enough to confirm the right person was found,
 * never enough to use — and there is no email, DOB, health note or emergency
 * contact. The nested `user` object is four keys and nothing else, which is
 * worth spelling out: `gender_display` sits at the *top* level, not under
 * `user`, and the list previously read it from the wrong place.
 */
import type { ChoiceDisplay } from "@/lib/choices";

export interface VolunteerPickerRow {
  /** The volunteer *profile* id. */
  id: number;
  /** The underlying user id — what the profile route needs. */
  user_id: number | null;
  nickname: string | null;
  full_name: string | null;
  profile_pic: string | null;
  gender_display: ChoiceDisplay | null;
  is_verified: boolean;
  /** Last four characters, or null when nothing is stored. */
  civil_id_last4: string | null;
  passport_last4: string | null;
  phone_last4: string | null;
  /** Exactly these four keys, or null when the profile has no user. */
  user: {
    id: number;
    full_name: string | null;
    profile_pic: string | null;
    nickname: string | null;
  } | null;
}

/** The id `direct-register/` takes for a row — the user, not the profile. */
export function pickerRowUserId(row: VolunteerPickerRow): number {
  return Number(row.user_id || row.user?.id || row.id);
}

/** The name the picker shows for a row; empty when the profile has none. */
export function pickerRowName(row: VolunteerPickerRow): string {
  return row.user?.full_name || row.full_name || row.nickname || "";
}

export interface DirectRegisterFailure {
  user_id: number | string;
  error: string;
}

export interface DirectRegisterFailureLine {
  userId: number;
  /** The picker name, or `#<id>` when the row is no longer loaded. */
  name: string;
  reason: string;
}

/**
 * `direct-register/` answers 201 when at least one person was added and 400
 * when none was, and in both cases lists every refused id under
 * `failed_registrations` with the reason: already registered, outside the
 * audience's gender, nationality or age range, no seat, and so on (backend
 * `b6ed21c`, BE-244). The reason is the backend's English text only — there is
 * no code to translate — so it is shown as sent.
 *
 * Reads the list off a success body or a failure body alike and pairs each id
 * with the name the organizer picked it by.
 */
export function directRegisterFailures(
  body: unknown,
  rows: ReadonlyArray<VolunteerPickerRow>,
): DirectRegisterFailureLine[] {
  const data = (body as { data?: { failed_registrations?: unknown } } | null)?.data;
  const failures = Array.isArray(data?.failed_registrations) ? data.failed_registrations : [];
  const names = new Map(rows.map((row) => [pickerRowUserId(row), pickerRowName(row)]));
  return failures.flatMap((entry) => {
    const failure = entry as Partial<DirectRegisterFailure> | null;
    const userId = Number(failure?.user_id);
    if (!Number.isFinite(userId)) return [];
    const reason = typeof failure?.error === "string" ? failure.error.trim() : "";
    return [{ userId, name: names.get(userId) || `#${userId}`, reason }];
  });
}

/** One line per refused person, for a toast description. */
export function formatDirectRegisterFailures(lines: ReadonlyArray<DirectRegisterFailureLine>): string {
  return lines.map((line) => (line.reason ? `${line.name}: ${line.reason}` : line.name)).join("\n");
}
