/**
 * Full audit (8 Nov 2026), volunteering area. Regression tests for the
 * frontend defects fixed in this round; see SC/cov/volunteer.md (F-VOL-n).
 */
import { test, describe } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { mapFormApiErrors } from "@/features/shared/formApiErrors";
import { VOLUNTEER_FIELD_ALIASES } from "@/features/opportunities/components/volunteerSubmitSteps";

const FORM_FIELDS = ["title_ar", "description_ar", "opportunity_images", "locationUrl", "link", "age", "isPrivate"];

const validationError = (errors: Record<string, string[]>) => ({
  response: {
    status: 422,
    data: { key: "fail", msg: "invalid", response_status: { error: true, validation_errors: errors } },
  },
});

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

describe("F-VOL-2 — server cover errors reach the upload field (PDF p.15)", () => {
  test("new_opportunity_images_0 maps to opportunity_images", () => {
    const mapped = mapFormApiErrors(
      validationError({ new_opportunity_images_0: ["The cover must be square."] }),
      "en", FORM_FIELDS, VOLUNTEER_FIELD_ALIASES,
    );
    assert.equal(mapped.opportunity_images, "The cover must be square.");
  });

  test("the existing aliases still map", () => {
    const mapped = mapFormApiErrors(
      validationError({ location_url: ["required"], whatsapp_link: ["bad"], from_age: ["ages"] }),
      "en", FORM_FIELDS, VOLUNTEER_FIELD_ALIASES,
    );
    assert.equal(mapped.locationUrl, "required");
    assert.equal(mapped.link, "bad");
    assert.equal(mapped.age, "ages");
  });
});

describe("F-VOL-1 — free volunteering registration success copy (A16)", () => {
  for (const file of [
    "features/opportunities/components/ConfirmVolunteerRegistrationModal.tsx",
    "features/opportunities/components/VolunteerRegisterRoleModal.tsx",
  ]) {
    test(`${file} shows «تم تسجيلك بنجاح», not the verify-email toast`, () => {
      const code = src(file);
      assert.match(code, /COMMON\.YOU_ARE_REGISTERED/);
      assert.doesNotMatch(code, /TOAST\.REGISTRATION_SUCCESSFUL/);
    });
  }

  test("the Arabic key is the approved sentence and mentions no email", () => {
    const ar = JSON.parse(readFileSync(new URL("../locales/ar/translation.json", import.meta.url), "utf8"));
    assert.equal(ar["COMMON.YOU_ARE_REGISTERED"], "تم تسجيلك بنجاح");
  });
});

describe("F-VOL-3/4 — stale caches after register / edit", () => {
  test("role registration invalidates the per-viewer detail", () => {
    assert.match(src("features/opportunities/components/VolunteerRegisterRoleModal.tsx"),
      /invalidateQueries\(\{ queryKey: \["volunteer-opportunity", opportunityId\] \}\)/);
  });

  test("an edit invalidates both the detail and the form source", () => {
    const code = src("features/opportunities/components/useVolunteerSubmit.ts");
    assert.match(code, /queryKey: \["volunteer-opportunity", id\]/);
    assert.match(code, /queryKey: \["opportunity-details", id\]/);
  });
});

describe("F-VOL-5 — creator rail shows the server's refusal and re-reads A15 state", () => {
  test("failures go through getApiErrorMessage and sending refetches", () => {
    const code = src("features/opportunities/components/volunteer-event/useCreatorActions.ts");
    assert.match(code, /getApiErrorMessage\(error, language, t\(failureKey\)\)/);
    assert.match(code, /getApiErrorMessage\(error, language, t\("COMMON\.TOAST\.CERTIFICATES_SEND_FAILED"\)\)/);
    assert.match(code, /getApiErrorMessage\(error, language, t\("COMMON\.TOAST\.MESSAGE_FAILED"\)\)/);
    assert.match(code, /NO_CERTIFICATES_TO_SEND"\)\);\s*\/\/[^\n]*\n[^\n]*\n\s*onChanged\(\);/);
  });
});

describe("F-VOL-6 — private share control wording (R14-10)", () => {
  test("OrganizerCard uses «مشاركة الفرصة»", () => {
    assert.match(src("features/opportunities/components/volunteer-event/OrganizerCard.tsx"), /COMMON\.SHARE_OPPORTUNITY/);
    const ar = JSON.parse(readFileSync(new URL("../locales/ar/translation.json", import.meta.url), "utf8"));
    assert.equal(ar["COMMON.SHARE_OPPORTUNITY"], "مشاركة الفرصة");
  });
});
