/**
 * Full audit, development area (8 Nov 2026) — regressions for the fixes made
 * in this round. See SC/cov/development.md, findings F-DEV-n.
 */
import { test, describe } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import moment from "moment";
import { developmentAttendanceOpensAt } from "@/features/opportunities/developmentAttendanceWindow";
import { canMarkDevelopmentAttendance } from "@/features/opportunities/components/useLearnServeCheckInWindow";
import { computeLearnServeViewState } from "@/features/opportunities/components/learnServeDetailsViewState";
import type { LearnServeOpportunityData } from "@/features/opportunities/components/learnServeDetailsTypes";

const at = (iso: string) => moment.parseZone(iso);
const lastDay = {
  id: "7",
  start_date: "2026-11-03",
  end_date: "2026-11-05",
  start_time: "18:00",
  end_time: "20:00",
  requires_check_in: true,
};

describe("F-DEV-1: manual attendance opens with the final-day scan (A14), not at midnight", () => {
  test("the server's scan_opens_at wins over the derived schedule", () => {
    const opens = developmentAttendanceOpensAt({ ...lastDay, scan_opens_at: "2026-11-05T17:30:00+03:00" });
    assert.equal(opens?.format(), "2026-11-05T17:30:00+03:00");
  });
  test("without the field the final-day session start is derived", () => {
    assert.equal(developmentAttendanceOpensAt(lastDay)?.format(), "2026-11-05T18:00:00+03:00");
  });
  test("the morning of the last day is refused, the session start is accepted", () => {
    assert.equal(canMarkDevelopmentAttendance(lastDay, at("2026-11-05T09:00:00+03:00")), false);
    assert.equal(canMarkDevelopmentAttendance(lastDay, at("2026-11-05T18:00:00+03:00")), true);
  });
  test("still closed after the preparation window", () => {
    assert.equal(canMarkDevelopmentAttendance({ ...lastDay, is_preparation_window_closed: true }, at("2026-11-06T10:00:00+03:00")), false);
  });
  test("the detail stash forwards scan_opens_at to the list", () => {
    const source = readFileSync("src/features/opportunities/components/learnServeRegisterListNavState.ts", "utf8");
    assert.match(source, /scan_opens_at: opportunityData\?\.scan_opens_at/);
  });
});

describe("F-DEV-2: attendance refusals and skipped unpaid seats reach the organizer", () => {
  const source = readFileSync("src/features/opportunities/components/useLearnServeRegisterListActions.ts", "utf8");
  test("the localized envelope is shown through toastApiError, never message_en", () => {
    assert.doesNotMatch(source, /message_en/);
    assert.match(source, /toastApiError\(error, selectedLanguage, t\("COMMON\.FAILED_TO_MARK_ATTENDED"\)\)/);
  });
  test("skipped seats re-read the list instead of flipping every selected row", () => {
    // Closure C-COORD-3: counted from the selection (`updated_count`), not the
    // course-wide `skipped_unpaid_count` the server sends.
    assert.match(source, /skippedFromSelection\(/);
    assert.match(source, /COMMON\.ATTENDANCE_SKIPPED_UNPAID/);
  });
  test("both languages carry the skipped message", () => {
    for (const lang of ["ar", "en"]) {
      const json = JSON.parse(readFileSync(`locales/${lang}/translation.json`, "utf8")) as Record<string, string>;
      assert.match(json["COMMON.ATTENDANCE_SKIPPED_UNPAID"] ?? "", /\{\{count\}\}/);
    }
  });
});

describe("F-DEV-3: a saved edit is not followed by the cached pre-edit record", () => {
  test("detail and form caches are invalidated after the update", () => {
    const source = readFileSync("src/features/opportunities/components/useLearnServeSubmit.ts", "utf8");
    assert.match(source, /invalidateQueries\(\{ queryKey: \["learn-serve-opportunity", String\(id\)\] \}\)/);
    assert.match(source, /invalidateQueries\(\{ queryKey: \["learn-serve-opportunity-form", id\] \}\)/);
  });
});

describe("F-DEV-4: free development registration success has no email wording (A16)", () => {
  test("the confirmation toasts «تم تسجيلك بنجاح», not the signup string", () => {
    const source = readFileSync("src/features/opportunities/components/ConfirmRegistrationModal.tsx", "utf8");
    assert.doesNotMatch(source, /COMMON\.TOAST\.REGISTRATION_SUCCESSFUL/);
    assert.match(source, /COMMON\.YOU_ARE_REGISTERED/);
    const ar = JSON.parse(readFileSync("locales/ar/translation.json", "utf8")) as Record<string, string>;
    assert.equal(ar["COMMON.YOU_ARE_REGISTERED"], "تم تسجيلك بنجاح");
  });
});

describe("F-DEV-5: organizer edit/delete follow the server capabilities", () => {
  const now = at("2026-11-01T12:00:00+03:00");
  const record = (over: Partial<LearnServeOpportunityData> = {}) => ({
    id: 77, primary_language: "ar", title_ar: "دورة", title_en: "دورة", description_ar: "<p>وصف</p>",
    start_date: "2026-11-03", end_date: "2026-11-05", start_time: "10:00", end_time: "12:00",
    opportunity_status: "upcoming", created_by: { id: 1 }, ...over,
  }) as LearnServeOpportunityData;
  const view = (over: Partial<LearnServeOpportunityData> = {}) => computeLearnServeViewState({
    opportunityData: record(over), isCreator: true, user: { id: 1, user_type: "organization" }, t: (key) => key, now,
  });
  test("can_edit / can_delete false disable the icons inside the client window", () => {
    assert.equal(view({ can_edit: false }).canEdit, false);
    assert.equal(view({ can_edit: false }).canDelete, false);
    assert.equal(view({ can_delete: false }).canEdit, true);
    assert.equal(view({ can_delete: false }).canDelete, false);
  });
  test("an older payload without the flags keeps the 24-hour rule", () => {
    assert.equal(view().canEdit, true);
    assert.equal(view().canDelete, true);
  });
});
