/**
 * Full audit (8 Nov 2026), Volunteer area part 2 — regressions for F-VOL2-n.
 */
import { test, describe } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { canAddVolunteerRole, isRoleCapacityWithinTotal } from "@/features/opportunities/roleCapacity";
import { shouldShowEmergencyContact } from "@/features/opportunities/registrationEmergencyContact";
import { permissionPerson, type PermissionRow } from "@/features/opportunities/components/attendancePermissionTypes";
import { isVolunteerListSourceMissing } from "@/features/opportunities/components/volunteer-event/volunteerListNavState";

const source = (path: string) => readFileSync(new URL(`../src/${path}`, import.meta.url), "utf8");

describe("F-VOL2-1 — PDF p.39: «إضافة دور» while seats remain", () => {
  test("adding is allowed with no roles and while roles leave seats free", () => {
    assert.equal(canAddVolunteerRole(10, 0), true);
    assert.equal(canAddVolunteerRole(10, 7), true);
  });
  test("refused once the roles account for every seat, or above it", () => {
    assert.equal(canAddVolunteerRole(10, 10), false);
    assert.equal(canAddVolunteerRole(10, 11), false);
    assert.equal(canAddVolunteerRole(0, 0), false);
    assert.equal(canAddVolunteerRole(Number.NaN, 0), false);
  });
  test("a valid total no longer disables the add button", () => {
    // The old gate was `disabled={hasValidParticipants}`, true for (10, 0).
    assert.equal(isRoleCapacityWithinTotal(10, 0), true);
    const modal = source("features/opportunities/components/VolunteerRoleModal.tsx");
    assert.match(modal, /disabled=\{!canAddRole\}/);
    assert.doesNotMatch(modal, /disabled=\{hasValidParticipants\}/);
  });
});

describe("F-VOL2-2 — attendance-permission holders keep email and phone", () => {
  const holder = {
    id: 42,
    full_name: "Delegate",
    email: "delegate@example.com",
    phone_number: "50000000",
    profile_pic: null,
    gender_display: null,
    is_allowed: true,
    attendance_permission_id: 7,
  } as unknown as PermissionRow;
  const candidate = {
    id: 900,
    user_id: 43,
    full_name: "Candidate",
    civil_id_last4: "1234",
    passport_last4: null,
    phone_last4: "9999",
    profile_pic: null,
    gender_display: null,
    user: { full_name: "Candidate", profile_pic: null },
  } as unknown as PermissionRow;

  test("a row from /attendance-permissions/list/ is read as a holder", () => {
    const person = permissionPerson(holder);
    assert.equal(person.id, 42);
    assert.equal(person.email, "delegate@example.com");
    assert.equal(person.phone, "50000000");
  });
  test("a picker row keys on user_id and shows only the masked hints", () => {
    const person = permissionPerson(candidate);
    assert.equal(person.id, 43);
    assert.equal(person.email, "");
    assert.deepEqual(person.identifiers, ["1234", "9999"]);
  });
});

describe("F-VOL2-3 — guardian columns follow the server's show_guardian_contact", () => {
  test("a year-only minor (no dob) still shows the guardian when the server says so", () => {
    assert.equal(
      shouldShowEmergencyContact({
        registration_date: "2026-10-01T10:00:00+03:00",
        user: { dob: null, show_guardian_contact: true, emergency_contact_name: "Guardian" },
      }),
      true,
    );
  });
  test("the server's false wins over a dob that looks minor", () => {
    assert.equal(
      shouldShowEmergencyContact({
        created_at: "2020-06-01",
        user: { dob: "2005-01-01", show_guardian_contact: false, emergency_contact_name: "Guardian" },
      }),
      false,
    );
  });
  test("still hidden when no contact field is stored", () => {
    assert.equal(
      shouldShowEmergencyContact({ user: { show_guardian_contact: true } }),
      false,
    );
  });
});

describe("F-VOL2-4 — QR scanner restarts the camera after a rejected code", () => {
  test("a failed submit re-runs the camera effect instead of only flipping `scanning`", () => {
    const hook = source("features/opportunities/components/useQrScanner.ts");
    assert.match(hook, /setArmCount\(\(count\) => count \+ 1\)/);
    assert.match(hook, /\[open, armCount, stopCamera, t, latestSubmit\]/);
  });
});

describe("F-VOL2-5 — /volunteerlist opened without the detail page's payload", () => {
  test("read-and-empty is reported; not-yet-read and a real id are not", () => {
    assert.equal(isVolunteerListSourceMissing({}), true);
    assert.equal(isVolunteerListSourceMissing({ id: "" }), true);
    assert.equal(isVolunteerListSourceMissing(null), false);
    assert.equal(isVolunteerListSourceMissing({ id: "12" }), false);
    assert.equal(isVolunteerListSourceMissing({ id: 12 }), false);
  });
});

describe("F-VOL2-6 — header live-scan list refreshes after a detail-page scan", () => {
  test("the detail self-scan invalidates the navbar's query", () => {
    const hook = source("features/opportunities/components/volunteer-event/useVolunteerSelfScan.ts");
    assert.match(hook, /invalidateQueries\(\{ queryKey: LIVE_ATTENDANCE_SCANS_KEY \}\)/);
  });
});

describe("F-VOL2-7 — delete-all-roles failure reads both error envelopes", () => {
  test("uses the shared helper rather than message_<lang> only", () => {
    const modal = source("features/opportunities/components/ParticipantsMismatchModal.tsx");
    assert.match(modal, /getApiErrorMessage\(error, selectedLanguage/);
    assert.doesNotMatch(modal, /message_\$\{selectedLanguage\}/);
  });
});
