/**
 * X1 «لم يسجل خروج»: the tag and the organizer alert follow the server's scan-out window
 * (up to 2 h after the session ends), and an undone attendance stops counting at once.
 */
import { test } from "node:test";
import assert from "node:assert/strict";
import { countMissedCheckOuts, missedCheckOutDays, withoutAttendance } from "@/features/opportunities/components/volunteerListHelpers";

const entry = (over: Record<string, unknown> = {}) => ({
  id: 11,
  attended_date: "2026-11-04",
  recorded_via: "qr_self",
  checked_in_at: "2026-11-04T20:05:00+03:00",
  checked_out_at: null,
  total_minutes: 0,
  ...over,
});

test("a session ending late evening is not 'missed' while the server still offers check-out", () => {
  // 00:30 on 5 Nov: the 4 Nov day is "before today", but the window is open until 01:00.
  const open = { attendances: [entry({ next_action: "check_out" })] };
  assert.deepEqual(missedCheckOutDays(open, "2026-11-05"), []);
  assert.equal(countMissedCheckOuts([open], "2026-11-05"), 0);
});

test("once the server closes the window the day is missed, even on the same calendar day", () => {
  const closed = { attendances: [entry({ next_action: null })] };
  assert.deepEqual(missedCheckOutDays(closed, "2026-11-04"), ["2026-11-04"]);
});

test("a payload without next_action falls back to the calendar day", () => {
  assert.deepEqual(missedCheckOutDays({ attendances: [entry()] }, "2026-11-05"), ["2026-11-04"]);
  assert.deepEqual(missedCheckOutDays({ attendances: [entry()] }, "2026-11-04"), []);
});

test("undoing an attendance removes it, so the tag and the alert count clear without a reload", () => {
  const row = { attendances: [entry({ next_action: null })], date_wise_attendance: [entry({ next_action: null })] };
  assert.equal(countMissedCheckOuts([row], "2026-11-05"), 1);
  const undone = withoutAttendance(row, 11);
  assert.equal(countMissedCheckOuts([undone], "2026-11-05"), 0);
  assert.equal(undone.attendances?.length, 0);
  const other = withoutAttendance(row, 999);
  assert.equal(other.attendances?.length, 1, "another id leaves the entry alone");
});

test("a null entry in the attendance list is ignored, not a crash", () => {
  const row = { attendances: [null, entry({ next_action: null })] } as unknown as Parameters<typeof missedCheckOutDays>[0];
  assert.deepEqual(missedCheckOutDays(row, "2026-11-05"), ["2026-11-04"]);
});
