/**
 * Opportunities closure regressions (8 Nov 2026, afternoon) — C-OPP-n.
 */
import { describe, test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { contactWhatsAppHref } from "@/lib/whatsapp";
import { externalHref } from "@/features/events/eventLifecycle";
import { getApiErrorMessage } from "@/lib/api/errors";

const src = (path: string) => readFileSync(new URL(`../src/${path}`, import.meta.url), "utf8");
const ar = JSON.parse(readFileSync(new URL("../locales/ar/translation.json", import.meta.url), "utf8")) as Record<string, string>;
const en = JSON.parse(readFileSync(new URL("../locales/en/translation.json", import.meta.url), "utf8")) as Record<string, string>;

describe("C-OPP-1 volunteer edit + resubmit failure shows the server reason", () => {
  test("the resubmit error is captured and passed to getApiErrorMessage", () => {
    const hook = src("features/opportunities/components/useVolunteerSubmit.ts");
    assert.match(hook, /resubmitError = error/);
    assert.match(hook, /getApiErrorMessage\(resubmitError, selectedLanguage, t\("COMMON\.TOAST\.RESUBMIT_FAILED"\)\)/);
  });
  test("a null error falls back to the generic key", () => {
    assert.equal(getApiErrorMessage(null, "ar", "fallback"), "fallback");
  });
  test("a paused-publisher refusal is the message shown", () => {
    const error = { response: { status: 403, data: { key: "fail", msg: "تم إيقاف النشر لحسابك", response_status: { error: true } } } };
    assert.equal(getApiErrorMessage(error, "ar", "fallback"), "تم إيقاف النشر لحسابك");
  });
});

describe("C-OPP-2 development message-all failure", () => {
  test("uses the server message", () => {
    assert.match(src("features/opportunities/components/LearnServeDetails.tsx"), /getApiErrorMessage\(error, selectedLanguage, t\("COMMON\.TOAST\.MESSAGE_FAILED"\)\)/);
  });
});

describe("C-OPP-3/4 failed list reads are errors, not empty lists", () => {
  test("volunteer roster exposes loadError and the section renders RegistrationsLoadError", () => {
    assert.match(src("features/opportunities/components/useVolunteerRegistrationsList.ts"), /loadError:\s*\n?\s*registrationsQuery\.isError && allRegistrations\.length === 0/);
    assert.match(src("features/opportunities/components/VolunteerListTableSection.tsx"), /if \(loadError\) return <RegistrationsLoadError/);
    assert.match(src("features/opportunities/components/VolunteerList.tsx"), /loadError=\{screen\.list\.loadError\}/);
  });
  test("add-volunteers picker shows the error instead of «لا يوجد متطوعين»", () => {
    assert.match(src("features/opportunities/components/useAvailableVolunteers.ts"), /availableVolunteersQuery\.isError && allVolunteers\.length === 0/);
    assert.match(src("features/opportunities/components/AvailableVolunteersList.tsx"), /\) : loadError \? \(/);
    assert.match(src("features/opportunities/components/AddVolunteersModal.tsx"), /loadError=\{picker\.loadError\}/);
  });
});

describe("C-OPP-5 volunteer sheet download", () => {
  test("duplicate guard and server reason", () => {
    const hook = src("features/opportunities/components/useVolunteerListExports.ts");
    assert.match(hook, /!opportunityId \|\| downloadMutation\.isPending/);
    assert.match(hook, /getApiErrorMessage\(error, language, t\("COMMON\.DOWNLOAD_FAILURE"\)\)/);
  });
});

describe("C-OPP-6 organizer contact links", () => {
  test("a scheme-less WhatsApp group link becomes an absolute https link (not dropped)", () => {
    assert.equal(contactWhatsAppHref("chat.whatsapp.com/AbC"), "https://chat.whatsapp.com/AbC");
    assert.equal(contactWhatsAppHref("55551234"), "https://wa.me/96555551234");
    assert.equal(contactWhatsAppHref("+965 5555 1234"), "https://wa.me/96555551234");
    assert.equal(contactWhatsAppHref("https://wa.me/96555551234"), "https://wa.me/96555551234");
    assert.equal(contactWhatsAppHref(""), "");
  });
  test("profile social links are http(s) only and gain a scheme", () => {
    assert.equal(externalHref("instagram.com/fursa"), "https://instagram.com/fursa");
    assert.equal(externalHref("javascript:alert(1)"), null);
    assert.equal(externalHref(""), null);
  });
  test("both cards use the helpers and a localized accessible name", () => {
    for (const file of ["features/opportunities/components/OrganizerContactLinks.tsx", "features/opportunities/components/volunteer-event/OrganizerCard.tsx"]) {
      const code = src(file);
      assert.match(code, /externalHref\(raw\)/, file);
      assert.match(code, /aria-label=\{t\(`COMMON\.SOCIAL_\$\{key\.replace\("_link", ""\)\.toUpperCase\(\)\}`\)\}/, file);
    }
    for (const key of ["FACEBOOK", "TWITTER", "WHATSAPP", "INSTAGRAM", "LINKEDIN"]) {
      assert.ok(ar[`COMMON.SOCIAL_${key}`] && en[`COMMON.SOCIAL_${key}`], key);
    }
  });
});

describe("C-OPP-7 no raw English aria-labels", () => {
  test("keys exist in both locales and the components use them", () => {
    for (const key of ["COMMON.SELECT_PERSON_NAMED", "COMMON.GO_TO_SLIDE", "COMMON.MARK_ATTENDANCE_FOR"]) {
      assert.ok(ar[key] && en[key], key);
    }
    assert.doesNotMatch(src("features/opportunities/components/AvailableVolunteersList.tsx"), /aria-label=\{`Select/);
    assert.doesNotMatch(src("features/opportunities/components/RegistrationRowCells.tsx"), /aria-label=\{`Select/);
    assert.doesNotMatch(src("features/opportunities/components/OpportunitySponsors.tsx"), /Go to slide/);
  });
});

describe("C-OPP-8 legacy «مساحة» slot booking", () => {
  test("A16 copy and the detail is invalidated", () => {
    const hook = src("features/opportunities/components/useConsultationBooking.ts");
    assert.match(hook, /t\("COMMON\.YOU_ARE_REGISTERED"\)/);
    assert.match(hook, /invalidateQueries\(\{ queryKey: \["learn-serve-opportunity", opportunityId\] \}\)/);
  });
});

describe("C-OPP-9 development completion gallery Save (F-UI-6 residual)", () => {
  test("the upload promise reaches UploadImageWithSave so Save stays disabled while it runs", () => {
    const gallery = src("features/opportunities/components/LearnServeCompletionGallery.tsx");
    assert.match(gallery, /onSave=\{\(\) =>\s*pendingFiles\.length > 0 \? onUpload\(pendingFiles\) : undefined/);
    for (const file of ["LearnServeCompletionGallery.tsx", "LearnServeDetailsColumn.tsx"]) {
      assert.match(src(`features/opportunities/components/${file}`), /onUpload: \(files: File\[\]\) => void \| Promise<unknown>;/, file);
    }
    assert.match(src("features/opportunities/components/useLearnServeMediaActions.ts"), /const handleFileUpload = async/);
  });
});
