/**
 * Closure "States" regressions (8 Nov 2026, C-STA-n): a failed read is an
 * error with a retry, never an empty / "not found" / "off" / "up to date" state (p.37).
 */
import { describe, test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { getReadErrorMessage, isNotFoundError } from "@/lib/api/errors";
import { certificatesSendState } from "@/features/opportunities/certificatesOutdated";
import { metadataText } from "@/lib/i18n/metadataCopy";

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

describe("C-STA-1 detail reads: only a 404 says «not found»", () => {
  test("404 without a message → not found; 500 / network → load failed; server message wins", () => {
    assert.equal(isNotFoundError({ response: { status: 404 } }), true);
    assert.equal(isNotFoundError({ response: { status: 500 } }), false);
    assert.equal(isNotFoundError(new Error("Network Error")), false);
    assert.equal(getReadErrorMessage({ response: { status: 404, data: {} } }, "ar", fallbacks), "NOT_FOUND");
    assert.equal(getReadErrorMessage({ response: { status: 500, data: "<html>" } }, "ar", fallbacks), "LOAD_FAILED");
    assert.equal(getReadErrorMessage(new Error("Network Error"), "en", fallbacks), "LOAD_FAILED");
    assert.equal(getReadErrorMessage({ response: { status: 404, data: { msg: "لم يتم العثور" } } }, "ar", fallbacks), "لم يتم العثور");
    assert.equal(getReadErrorMessage({ response: { status: 403, data: { message_ar: "ممنوع", message_en: "Forbidden" } } }, "en", fallbacks), "Forbidden");
  });

  test("CommonProfile, EventDetails and LearnServeDetailsUnavailable use it", () => {
    for (const file of ["features/profile/components/CommonProfile.tsx", "features/events/components/EventDetails.tsx", "features/opportunities/components/LearnServeDetailsUnavailable.tsx"]) {
      assert.match(src(file), /getReadErrorMessage\(/, file);
      assert.match(src(file), /COMMON\.DETAILS_LOAD_FAILED/, file);
    }
    assert.doesNotMatch(src("features/profile/components/CommonProfile.tsx"), /"Profile not found"/);
  });
});

describe("C-STA-2 «إرسال الشهادات» is never enabled on data that did not load (A15)", () => {
  test("loading and failed reads block Send with their own reason", () => {
    assert.deepEqual(certificatesSendState({ hasData: false, isError: false, source: undefined }), { needsSending: false, blockedReason: "loading" });
    assert.deepEqual(certificatesSendState({ hasData: false, isError: true, source: undefined }), { needsSending: false, blockedReason: "load-failed" });
  });

  test("a failed refetch after a send does not re-enable Send from the stale «outdated» flag", () => {
    assert.deepEqual(certificatesSendState({ hasData: true, isError: true, source: { certificates_outdated: true } }), { needsSending: false, blockedReason: "load-failed" });
  });

  test("loaded data keeps the server rule; an older API without the field stays enabled", () => {
    assert.deepEqual(certificatesSendState({ hasData: true, isError: false, source: { certificates_outdated: true } }), { needsSending: true, blockedReason: null });
    assert.deepEqual(certificatesSendState({ hasData: true, isError: false, source: { certificates_outdated: false } }), { needsSending: false, blockedReason: "up-to-date" });
    assert.deepEqual(certificatesSendState({ hasData: true, isError: false, source: {} }), { needsSending: true, blockedReason: null });
  });

  test("both lists explain a failed read and offer a retry", () => {
    assert.match(src("features/opportunities/components/VolunteerList.tsx"), /CertificatesStateError/);
    assert.match(src("features/opportunities/components/RegisterListToolbar.tsx"), /CertificatesStateError/);
    assert.match(src("features/opportunities/components/RegisterListForLearnandServe.tsx"), /onRetryCertificates=\{certificates\.retry\}/);
  });
});

describe("C-STA-3..6 supplementary reads say they failed", () => {
  test("refund notice: a failed payment read keeps «ملغاة» and says the refund state did not load (never «refunded»)", () => {
    const file = src("features/opportunities/components/CancelledCourseRefundNotice.tsx");
    assert.match(file, /payment\.isError && !isNotFoundError\(payment\.error\)/);
    assert.match(file, /COMMON\.REFUND_STATE_LOAD_FAILED/);
  });

  test("participants & payments: people lookup failure is announced with a retry", () => {
    assert.match(src("features/opportunities/components/useParticipantsPayments.ts"), /peopleFailed: peopleQuery\.isError/);
    assert.match(src("features/opportunities/components/ParticipantsPayments.tsx"), /COMMON\.PARTICIPANT_DETAILS_LOAD_FAILED/);
  });

  test("quiet mode: no «off» switch when the profile failed to load", () => {
    const file = src("features/profile/components/individual/QuietModeCard.tsx");
    assert.match(file, /\(data \|\| !isError\) && <Toggle/);
    assert.match(file, /COMMON\.QUIET_MODE_LOAD_FAILED/);
  });

  test("bank change card: shown from the session when the account read fails; state failure has a retry", () => {
    const file = src("features/profile/components/PayoutBankChangeCard.tsx");
    assert.match(file, /account\.isError && !account\.data/);
    assert.match(file, /state\.refetch\(\)/);
  });

  test("new keys exist in both languages", () => {
    for (const lang of ["ar", "en"] as const) {
      const l = locale(lang);
      for (const key of ["PARTICIPANT_DETAILS_LOAD_FAILED", "CERTIFICATES_STATE_LOAD_FAILED", "REFUND_STATE_LOAD_FAILED", "QUIET_MODE_LOAD_FAILED", "PROFILE_NOT_FOUND", "DETAILS_LOAD_FAILED"]) {
        assert.ok(l[`COMMON.${key}`], `${lang} COMMON.${key}`);
      }
    }
  });
});

test("C-STA-7 team sign-up metadata is localized like its sibling sign-up pages", () => {
  assert.equal(metadataText("Volunteer team registration", "ar"), "تسجيل فريق تطوعي");
  assert.equal(metadataText("Create a volunteer team account on Fursa.", "ar"), "أنشئ حساب فريق تطوعي في منصة فرصة.");
});
