/**
 * ClosureB file-level audit regressions (8 Nov 2026).
 */
import { describe, test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import type { QueryClient } from "@tanstack/react-query";
import { initialPagedState, nextPagedState } from "@/features/shared/pagedList";
import {
  refreshVolunteerRegistrations,
  volunteerRegistrationsKey,
} from "@/features/opportunities/components/volunteerRegistrationsRefresh";
import type { ApiResponse } from "@/lib/api/types";

type Row = { id: number };
const page = (n: number, ids: number[]): ApiResponse<Row[]> =>
  ({
    key: "success",
    msg: "",
    code: 200,
    response_status: { error: false },
    data: ids.map((id) => ({ id })),
    meta: { pagination: { page: n, limit: 2, total: 4, total_pages: 2 } },
  }) as unknown as ApiResponse<Row[]>;

describe("F-CLB-1 volunteer roster refresh after a write", () => {
  test("a refetched page 2 is ignored, so refetching the current page cannot drop an excluded row", () => {
    const input = { resetSignature: "", isFetching: false, limit: 2 };
    let state = nextPagedState(initialPagedState<Row>(""), { ...input, response: page(1, [1, 2]) })!;
    state = nextPagedState(state, { ...input, response: page(2, [3, 4]) })!;
    // Row 1 excluded; the old code refetched only page 2.
    assert.equal(nextPagedState(state, { ...input, response: page(2, [4]) }), null);
    // A page-1 reload replaces the list.
    const reloaded = nextPagedState(state, { ...input, response: page(1, [2, 3]) })!;
    assert.deepEqual(reloaded.items.map((r) => r.id), [2, 3]);
  });

  test("refresh resets the cursor and invalidates every page of that opportunity", async () => {
    const calls: string[] = [];
    const client = {
      invalidateQueries: async ({ queryKey }: { queryKey: readonly unknown[] }) => {
        calls.push(`invalidate:${JSON.stringify(queryKey)}`);
      },
    } as unknown as QueryClient;
    await refreshVolunteerRegistrations(client, "42", () => calls.push("reset"));
    assert.deepEqual(calls, ["reset", `invalidate:${JSON.stringify(["volunteer-registrations", "42"])}`]);
    assert.deepEqual(volunteerRegistrationsKey("42"), ["volunteer-registrations", "42"]);
  });
});

describe("F-CLB-2 organizer message hint (A17: always-send email)", () => {
  for (const lang of ["ar", "en"]) {
    test(`${lang} hint does not claim Do Not Disturb blocks the email`, () => {
      const dict = JSON.parse(readFileSync(`locales/${lang}/translation.json`, "utf8"));
      const hint: string = dict["COMMON.MESSAGE_REGISTRANTS_HINT"];
      assert.ok(hint);
      assert.doesNotMatch(hint, /Do Not Disturb|عدم الإزعاج/);
    });
  }

  test("attendance checkbox label key exists in both languages", () => {
    for (const lang of ["ar", "en"]) {
      const dict = JSON.parse(readFileSync(`locales/${lang}/translation.json`, "utf8"));
      assert.match(dict["COMMON.MARK_ATTENDANCE_FOR"], /\{\{name\}\}/);
    }
  });
});
