/**
 * "Select all" on the bulk-attendance table, across paging and date changes.
 *
 * The table loads registrations a page at a time. The question these cover is
 * what happens to a header-level "select all" when a *later* page arrives, and
 * what happens when the organizer switches day — the two moments where the
 * previous implementation went wrong.
 *
 * It went wrong because the selection was *extended* per merged page by a
 * callback that was passed `opportunity_end_date` where
 * `opportunity_end_time` belongs. `canMarkAttendanceForDate` split
 * `"2026-10-05"` on `":"`, so `endHours = 2026` and `endMinutes = NaN`, the
 * same-day comparison was against an Invalid Date, and every volunteer who
 * had registered on the selected day was silently skipped. The header toggle
 * passed the real end time, so the two code paths disagreed about the same
 * rows. There is now one path, derived, and the cases below are what pin it.
 */
import { test, describe } from "node:test";
import assert from "node:assert/strict";
import {
  effectiveAttendanceSelection,
  selectableAttendanceUuids,
  type AttendanceRow,
} from "@/features/opportunities/components/volunteerListHelpers";

const START = "2026-10-01";
const END_TIME = "17:00";

/** Registered at 09:00 on the given day. */
const row = (
  uuid: string,
  registeredOn: string,
  attended: string[] = [],
  time = "09:00:00"
): AttendanceRow => ({
  volunteer_uuid: uuid,
  registration_date: `${registeredOn}T${time}`,
  date_wise_attended: attended,
});

const selectAll = (rows: AttendanceRow[], date: string) =>
  effectiveAttendanceSelection({
    selectAllMode: true,
    manualTracking: true,
    rows,
    date,
    opportunity_start_date: START,
    opportunity_end_time: END_TIME,
    explicitSelection: [],
  });

describe("select-all across pagination", () => {
  const page1 = [row("a", START), row("b", START)];
  const page2 = [row("c", START), row("d", START)];

  test("the first page is selected", () => {
    assert.deepEqual(selectAll(page1, "2026-10-03"), ["a", "b"]);
  });

  test("a page that arrives later is included, with no extension step", () => {
    /*
     * The derivation is over whatever rows are loaded, so merging page 2 is
     * the whole of what has to happen. Nothing re-runs a per-page callback,
     * which is what could previously run with the wrong arguments.
     */
    assert.deepEqual(selectAll([...page1, ...page2], "2026-10-03"), [
      "a",
      "b",
      "c",
      "d",
    ]);
  });

  test("a row already marked present on that day is never selected", () => {
    const rows = [row("a", START, ["2026-10-03"]), row("b", START)];
    assert.deepEqual(selectAll(rows, "2026-10-03"), ["b"]);
  });

  test("a download row with no uuid is dropped rather than selected as empty", () => {
    const rows: AttendanceRow[] = [
      { registration_date: `${START}T09:00:00`, date_wise_attended: [] },
      row("b", START),
    ];
    assert.deepEqual(selectAll(rows, "2026-10-03"), ["b"]);
  });

  test("with the mode off, a later page adds nothing", () => {
    const withModeOff = (rows: AttendanceRow[]) =>
      effectiveAttendanceSelection({
        selectAllMode: false,
        manualTracking: true,
        rows,
        date: "2026-10-03",
        opportunity_start_date: START,
        opportunity_end_time: END_TIME,
        explicitSelection: ["a"],
      });

    assert.deepEqual(withModeOff(page1), ["a"]);
    // This is the untick case: the mode is gone, so page 2 must not be swept in.
    assert.deepEqual(withModeOff([...page1, ...page2]), ["a"]);
  });

  test("QR-tracked opportunities have no derived selection at all", () => {
    assert.deepEqual(
      effectiveAttendanceSelection({
        selectAllMode: true,
        manualTracking: false,
        rows: page1,
        date: "2026-10-03",
        opportunity_start_date: START,
        opportunity_end_time: END_TIME,
        explicitSelection: [],
      }),
      []
    );
  });
});

describe("the same-day registrant — the defect this replaced", () => {
  test("someone who registered before the session ended is selectable", () => {
    const sameDay = [row("late", "2026-10-03", [], "10:30:00")];
    assert.deepEqual(selectAll(sameDay, "2026-10-03"), ["late"]);
  });

  test("someone who registered after it ended is not", () => {
    const tooLate = [row("after", "2026-10-03", [], "18:30:00")];
    assert.deepEqual(selectAll(tooLate, "2026-10-03"), []);
  });

  test("passing a DATE where the END TIME belongs loses them — the old bug", () => {
    /*
     * This is the exact mistake, reproduced: a `Y-m-d` in the
     * `opportunity_end_time` slot. `"2026-10-05".split(":")` is
     * `["2026-10-05"]`, so `endMinutes` is `NaN` and the comparison is against
     * an Invalid Date.
     *
     * It is asserted rather than merely described so that nobody "fixes" the
     * signature by widening it to accept a date, which would make the failure
     * silent again.
     */
    const sameDay = [row("late", "2026-10-03", [], "10:30:00")];

    const withDateAsTime = effectiveAttendanceSelection({
      selectAllMode: true,
      manualTracking: true,
      rows: sameDay,
      date: "2026-10-03",
      opportunity_start_date: START,
      opportunity_end_time: "2026-10-05",
      explicitSelection: [],
    });
    assert.deepEqual(withDateAsTime, []);

    // …while the real end time finds them.
    assert.deepEqual(selectAll(sameDay, "2026-10-03"), ["late"]);
  });

  test("a volunteer who registered after the selected day is not selectable", () => {
    const later = [row("future", "2026-10-07")];
    assert.deepEqual(selectAll(later, "2026-10-03"), []);
  });

  test("a volunteer who registered earlier is selectable on any later day", () => {
    const earlier = [row("early", START)];
    assert.deepEqual(selectAll(earlier, "2026-10-09"), ["early"]);
  });
});

describe("changing the date re-answers the selection", () => {
  /*
   * The hook clears the explicit ticks when `selectedDate` changes — a tick
   * entered for Monday must never be submitted against Tuesday. These cases
   * cover the other half: that the *derived* answer is per-date too, so the
   * mode surviving a date change cannot carry a stale row with it.
   */
  const rows = [
    row("a", START, ["2026-10-03"]),
    row("b", START),
    row("c", "2026-10-05"),
  ];

  test("on the 3rd: `a` is already present, `c` has not registered yet", () => {
    assert.deepEqual(selectAll(rows, "2026-10-03"), ["b"]);
  });

  test("on the 6th: `a` is selectable again and `c` has joined", () => {
    assert.deepEqual(selectAll(rows, "2026-10-06"), ["a", "b", "c"]);
  });

  test("the same rows give different answers per date, with no state between", () => {
    const third = selectAll(rows, "2026-10-03");
    const sixth = selectAll(rows, "2026-10-06");
    const thirdAgain = selectAll(rows, "2026-10-03");
    assert.deepEqual(thirdAgain, third);
    assert.notDeepEqual(sixth, third);
  });

  test("the derivation matches `selectableAttendanceUuids` exactly", () => {
    /*
     * The header checkbox's "is everything selected?" check calls
     * `selectableAttendanceUuids` directly. If the two ever diverge the box
     * shows a state the submission does not match, which is the class of bug
     * the old two-path version had.
     */
    for (const date of ["2026-10-03", "2026-10-06", "2026-10-09"]) {
      assert.deepEqual(
        selectAll(rows, date),
        selectableAttendanceUuids(rows, date, START, END_TIME)
      );
    }
  });
});
