/**
 * Full-stack audit (8 Nov 2026, backend 409e2f4), volunteering — regressions for S-VOL-n.
 */
import { test, describe } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { normalizeSessionUser, useAuthStore, type User } from "@/store/authStore";
import { getPublishPermissions } from "@/lib/publishPermissions";
import { routeAccess } from "@/components/shared/routeAccess";
import { runVolunteerCreate } from "@/features/opportunities/components/volunteerSubmitSteps";
import {
  countMissedCheckOuts,
  missedCheckOutDays,
  withCorrectedAttendance,
  type AttendanceEntry,
} from "@/features/opportunities/components/volunteerListHelpers";

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

/* What `WebsiteLoginUserResource` returns for a team since team sign-up. */
const team = {
  id: 41, user_type: "voluntary_team", is_verified: true, is_banned: false, is_publishing_paused: false,
  organizer_type_display: { value_en: "Volunteer Team" }, auth_token: "t",
  organization: { id: 9, organization_status: "approved" },
} as unknown as User;

describe("S-VOL-1 — p.41 / X2: a voluntary team signs in as an organizer", () => {
  test("the session user is normalized to the organization side", () => {
    assert.equal(normalizeSessionUser(team).user_type, "organization");
    const volunteer = { ...team, user_type: "volunteer" } as User;
    assert.equal(normalizeSessionUser(volunteer), volunteer);
  });
  test("setUser stores the normalized type, so guards and the publish menu see an organizer", () => {
    useAuthStore.setState({ user: null, accounts: [] });
    useAuthStore.getState().setUser(team);
    const stored = useAuthStore.getState().user!;
    assert.equal(stored.user_type, "organization");
    const permissions = getPublishPermissions(stored);
    assert.equal(permissions.volunteer, true);
    assert.equal(permissions.events, false);
    assert.equal(routeAccess({ user: stored, publish: "volunteer" }).allow, true);
    assert.equal(routeAccess({ user: stored, userType: "organization" }).allow, true);
    useAuthStore.setState({ user: null, accounts: [] });
  });
  test("a stored pre-fix team session is normalized on rehydration", () => {
    assert.match(source("store/authStore.ts"), /merge: \(persisted, current\)[\s\S]*normalizeSessionUser\(saved\.user\)/);
  });
});

describe("S-VOL-2 — p.13: a sponsor refusal after a successful create keeps the record", () => {
  test("the outcome carries the id and the sponsor error instead of throwing", async () => {
    const refusal = new Error("edit_window_closed");
    const outcome = await runVolunteerCreate({
      formData: new FormData(),
      sponsorIds: ["5"],
      steps: {
        create: async () => ({ interestsDropped: false, opportunityId: "90" }),
        syncSponsors: async () => { throw refusal; },
      },
    });
    assert.equal(outcome.opportunityId, "90");
    assert.equal(outcome.sponsorError, refusal);
  });
  test("the hook still records the id and shows the sponsor message", () => {
    const hook = source("features/opportunities/components/useVolunteerSubmit.ts");
    assert.match(hook, /outcome\.sponsorError !== undefined/);
  });
});

describe("S-VOL-3 — p.39: «غير محدد» is not sent as a role move", () => {
  test("an empty role value returns before the mutation", () => {
    const hook = source("features/opportunities/hooks/useTeamsAndRoles.ts");
    assert.match(hook, /if \(!value\) return;\s*try \{/);
  });
});

const arrival = (extra: Partial<AttendanceEntry> = {}): AttendanceEntry => ({
  id: 7, attended_date: "2026-11-08", recorded_via: "qr_self", checked_in_at: "2026-11-08T08:00:00+03:00",
  checked_out_at: null, total_minutes: 0, total_hours: 0, hours_set_manually_at: null, ...extra,
});

describe("S-VOL-4 — X1: an hours fix clears «لم يسجل خروج» at once", () => {
  test("the corrected day becomes organizer-owned and stops counting", () => {
    const row = { attendances: [arrival({ attended_date: "2026-11-07" }), arrival({ id: 8, attended_date: "2026-11-06" })] };
    assert.equal(missedCheckOutDays(row, "2026-11-08").length, 2);
    const fixed = withCorrectedAttendance(row, 7, { total_hours: 3, total_minutes: 180, hours_set_manually_at: "2026-11-08T10:00:00+03:00" });
    assert.deepEqual(missedCheckOutDays(fixed, "2026-11-08"), ["2026-11-06"]);
    assert.equal(fixed.attendances![0].total_minutes, 180);
    assert.equal(row.attendances[0].total_minutes, 0, "the original row is not mutated");
  });
  test("the hook patches the roster rows after a save", () => {
    assert.match(source("features/opportunities/hooks/useVolunteerAttendance.ts"), /withCorrectedAttendance\(row, attendanceId/);
  });
});

describe("S-VOL-5 — X1: missing check-out follows the server's scan-window close", () => {
  test("same day, window closed (next_action null) → missing", () => {
    assert.equal(countMissedCheckOuts([{ attendances: [arrival({ next_action: null })] }], "2026-11-08"), 1);
  });
  test("past midnight but window still open (overnight, next_action check_out) → not yet on the same day", () => {
    assert.deepEqual(missedCheckOutDays({ attendances: [arrival({ next_action: "check_out" })] }, "2026-11-08"), []);
  });
  test("payloads without next_action keep the day-before-today rule", () => {
    assert.deepEqual(missedCheckOutDays({ attendances: [arrival()] }, "2026-11-08"), []);
    assert.deepEqual(missedCheckOutDays({ attendances: [arrival()] }, "2026-11-09"), ["2026-11-08"]);
  });
});

describe("S-VOL-6 — product digit rule: Arabic dates keep Western digits", () => {
  test("ban notice and registration deadline use the latn numbering system", () => {
    for (const path of ["components/shared/BanNoticeModal.tsx", "features/opportunities/components/RegistrationDeadlineText.tsx"]) {
      const file = source(path);
      assert.match(file, /"ar-KW-u-nu-latn"/);
      assert.doesNotMatch(file, /"ar-KW"/);
    }
    assert.match(new Intl.DateTimeFormat("ar-KW-u-nu-latn", { year: "numeric" }).format(new Date(2026, 0, 1)), /2026/);
  });
});
