/**
 * Closure whole-app sweep regressions (8 Nov 2026, C-SWP-n).
 */
import { describe, test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { createAppQueryClient, isReferenceQuery, markServerReadsStale } from "@/providers/mutationStaleness";
import { createTranslationInstance } from "@/lib/i18n/config";
import { externalHref } from "@/features/events/eventLifecycle";
import { contactWhatsAppHref } from "@/lib/whatsapp";

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 tick = () => new Promise((resolve) => setTimeout(resolve, 0));

describe("C-SWP-1 every successful mutation marks server reads stale", () => {
  test("reference data (choices, CMS, settings) is not a server read a write changes", () => {
    assert.equal(isReferenceQuery(["dropdown", "gender"]), true);
    assert.equal(isReferenceQuery(["gender-choices"]), true);
    assert.equal(isReferenceQuery(["home-cms"]), true);
    assert.equal(isReferenceQuery(["user-opportunities", 1]), false);
    assert.equal(isReferenceQuery(["learn-serve-opportunity", "5", true]), false);
  });

  test("a mutation success invalidates lists/profile/detail without refetching, and leaves choices fresh", async () => {
    const client = createAppQueryClient();
    let fetches = 0;
    const observerKey = ["opportunities-feed", true];
    await client.fetchQuery({ queryKey: observerKey, queryFn: async () => { fetches += 1; return [1]; } });
    client.setQueryData(["user-opportunities-counts"], { all: 1 });
    client.setQueryData(["dropdown", "gender"], ["m", "f"]);

    await client.getMutationCache().build(client, { mutationFn: async () => "ok" }).execute(undefined);
    await tick();

    assert.equal(client.getQueryState(observerKey)?.isInvalidated, true);
    assert.equal(client.getQueryState(["user-opportunities-counts"])?.isInvalidated, true);
    assert.equal(client.getQueryState(["dropdown", "gender"])?.isInvalidated, false);
    assert.equal(fetches, 1, "refetchType none: nothing reloads under the current screen");
  });

  test("a failed mutation changes nothing", async () => {
    const client = createAppQueryClient();
    client.setQueryData(["user-opportunities"], []);
    await client.getMutationCache().build(client, { mutationFn: async () => { throw new Error("no"); } })
      .execute(undefined).catch(() => undefined);
    await tick();
    assert.equal(client.getQueryState(["user-opportunities"])?.isInvalidated, false);
  });

  test("the provider uses the factory, and the direct (non-mutation) deletion asks for it", async () => {
    assert.match(src("providers/query.tsx"), /createAppQueryClient\(/);
    assert.match(src("features/opportunities/components/DeleteOpportunityModal.tsx"), /markServerReadsStale\(queryClient\)/);
    const calls: unknown[] = [];
    await markServerReadsStale({ invalidateQueries: async (filters?: unknown) => { calls.push(filters); } } as never);
    assert.equal((calls[0] as { refetchType: string }).refetchType, "none");
  });
});

describe("C-SWP-2 failed reads render an error, not an empty state", () => {
  const cases: Array<[string, RegExp]> = [
    ["features/home/components/Events.tsx", /isError && events\.length === 0[\s\S]*QueryErrorNotice/],
    ["features/partners/components/Partner.tsx", /loadError \?[\s\S]*QueryErrorNotice[\s\S]*NO_SPONSORS/],
    ["features/trainer/components/TrainerRequestSection.tsx", /if \(isError\) return <QueryErrorNotice/],
    ["features/community/components/UserReply.tsx", /if \(repliesError\) return <QueryErrorNotice/],
    ["features/community/components/ReplyDetailPage.tsx", /if \(loadError\) return <QueryErrorNotice/],
    ["features/community/components/CreatePostModal.tsx", /if \(detailsError\) return <QueryErrorNotice/],
    ["features/community/components/ReplyForm.tsx", /if \(detailsError\) return <QueryErrorNotice/],
    ["features/community/components/ReplyOfReplyForm.tsx", /if \(detailsError\) return <QueryErrorNotice/],
    ["features/opportunities/components/AttendancePermissionModal.tsx", /holdersError \?[\s\S]*QueryErrorNotice/],
    ["features/opportunities/components/VolunteerRoleModal.tsx", /if \(loadError\) return <QueryErrorNotice/],
    ["features/opportunities/components/CreateVolunteerRoleModal.tsx", /if \(roleError \|\| limits\.isError\) return <QueryErrorNotice/],
    ["features/opportunities/components/PayoutBankFields.tsx", /if \(isOrganization && isError\)\s*\{\s*return <QueryErrorNotice/],
  ];
  for (const [path, pattern] of cases) test(path, () => assert.match(src(path), pattern));

  test("a failed reply read no longer navigates back as if the link were stale", () => {
    assert.match(src("features/community/components/useReplyDetail.ts"), /!isLoading && !isError &&/);
  });
  test("the decorative achievements banner hides on error instead of «no record yet»", () => {
    assert.match(src("features/community/components/AddBanner.tsx"), /if \(isError && !topIndividual\) return null;/);
  });
});

describe("C-SWP-3 like failures show the server's reason", () => {
  for (const file of ["useCommunityDetail", "useInnerPost", "useReplyDetail", "useUserReply"]) {
    test(file, () => {
      const code = src(`features/community/components/${file}.ts`);
      assert.match(code, /getApiErrorMessage\(\w+, selectedLanguage, t\("COMMON\.LIKE_FAILED"\)\)/);
      assert.doesNotMatch(code, /toast\.error\(t\("COMMON\.LIKE_FAILED"\)\)/);
    });
  }
});

describe("C-SWP-4 consequential actions cannot fire twice", () => {
  test("delete-all-roles stays disabled through the post-success settle delay", () => {
    const code = src("features/opportunities/components/ParticipantsMismatchModal.tsx");
    assert.match(code, /isPending \|\| deleteAllRolesMutation\.isSuccess/);
    assert.match(code, /if \(busy\) return;/);
  });
  test("profile picture / logo Save awaits the upload and is disabled meanwhile", () => {
    const code = src("features/profile/components/ProfilePictureCropModal.tsx");
    assert.match(code, /await onCropComplete\(croppedImage\)/);
    assert.match(code, /loading=\{saving\}/);
  });
  test("Enter in the hours cell, resend OTP and the downloads check the pending flag", () => {
    assert.match(src("features/opportunities/components/AttendanceHoursCell.tsx"), /if \(!isSavingHours\) void onSaveHours/);
    assert.match(src("features/auth/components/useEmailVerification.ts"), /isResendDisabled \|\| resendOtpMutation\.isPending/);
    assert.match(src("features/auth/components/EmailVerificationForm.tsx"), /disabled=\{isResendDisabled \|\| isResendLoading\}/);
    assert.match(src("features/opportunities/components/volunteer-event/useCompletionGallery.ts"), /if \(downloadMutation\.isPending\) return;/);
    assert.match(src("features/opportunities/components/useLearnServeMediaActions.ts"), /if \(downloadImageMutation\.isPending\) return;/);
    assert.match(src("features/opportunities/components/useLearnServeRegisterListActions.ts"), /if \(downloadMutation\.isPending\) return;/);
  });
});

describe("C-SWP-5 no hard-coded English in live accessible names", () => {
  test("password toggles are translated", () => {
    for (const file of ["components/ui/Input.tsx", "components/ui/ModalInput.tsx"]) {
      assert.doesNotMatch(src(file), /"Show password"|"Hide password"/);
      assert.match(src(file), /COMMON\.SHOW_PASSWORD/);
    }
  });
  test("new keys exist in both languages", () => {
    for (const lang of ["ar", "en"] as const) {
      for (const key of ["COMMON.SHOW_PASSWORD", "COMMON.HIDE_PASSWORD", "COMMON.COMPLETED_OPPORTUNITY_IMAGE"]) {
        assert.ok(locale(lang)[key], `${lang} ${key}`);
      }
    }
  });
  test("consultation slot table headers follow the reading direction", () => {
    assert.doesNotMatch(src("features/events/components/EventTimeSlotTable.tsx"), /text-left/);
  });
});

describe("C-SWP-6 external links built from stored data carry a scheme", () => {
  test("helpers turn `www.` and bare numbers into absolute URLs", () => {
    assert.equal(externalHref("www.example.com"), "https://www.example.com/");
    assert.equal(externalHref("javascript:alert(1)"), null);
    assert.match(contactWhatsAppHref("96512345678"), /^https:\/\/wa\.me\//);
  });
  const files = [
    "features/profile/components/individual/ProfileSocialRow.tsx",
    "features/events/components/EventDetailsAside.tsx",
    "features/home/components/BannerCarousel.tsx",
    "components/shared/PlacementBanner.tsx",
    "components/layout/Footer.tsx",
  ];
  for (const file of files) {
    test(file, () => {
      const code = src(file);
      assert.match(code, /externalHref\(/);
      assert.doesNotMatch(code, /href=\{banner\.banner_url\}|href=\{social\[key\] as string\}|\?\.trim\(\) \?\? ""/);
    });
  }
});

describe("C-SWP-7 count strings have plural forms", () => {
  const en = createTranslationInstance("en");
  const ar = createTranslationInstance("ar");
  test("English singular/plural", () => {
    assert.equal(en.t("COMMON.BAN_DURATION_DAYS", { count: 1 }), "Ban duration: 1 day");
    assert.equal(en.t("COMMON.TOAST.CERTIFICATES_SENT", { count: 1 }), "1 certificate sent");
    assert.equal(en.t("COMMON.PARTICIPANTS_STILL_NEEDED", { count: 1 }), "1 participant still needed");
    assert.equal(en.t("COMMON.ATTENDANCE_SKIPPED_UNPAID", { count: 2 }), "2 participants were not marked: their payment is not complete.");
  });
  test("Arabic dual and 3–10 forms", () => {
    assert.equal(ar.t("COMMON.BAN_DURATION_DAYS", { count: 2 }), "مدة الحظر: يومان");
    assert.equal(ar.t("COMMON.BAN_DURATION_DAYS", { count: 7 }), "مدة الحظر: 7 أيام");
    assert.equal(ar.t("COMMON.BAN_DURATION_DAYS", { count: 30 }), "مدة الحظر: 30 يومًا");
    assert.equal(ar.t("COMMON.TOAST.CERTIFICATES_SENT", { count: 3 }), "تم إرسال 3 شهادات");
  });
  test("every Arabic plural set is complete", () => {
    const ar = locale("ar");
    const bases = new Set(Object.keys(ar).filter((k) => /_(zero|one|two|few|many|other)$/.test(k)).map((k) => k.replace(/_(zero|one|two|few|many|other)$/, "")));
    for (const base of bases) {
      for (const form of ["zero", "one", "two", "few", "many", "other"]) assert.ok(`${base}_${form}` in ar, `${base}_${form}`);
    }
  });
});

describe("C-SWP-8 KWD and dates", () => {
  test("economic impact keeps the dinar's three decimals", () => {
    assert.match(src("features/achievements/components/useAchievements.ts"), /minimumFractionDigits: 3, maximumFractionDigits: 3/);
  });
  test("slot dates are not parsed as UTC midnight in the browser's zone", () => {
    const code = src("features/events/components/useEventTimeSlots.ts");
    assert.doesNotMatch(code, /new Date\(slot\.date\)\.toLocaleDateString\(\)/);
    assert.match(code, /formatForDisplay\(slot\.date, i18n\.language\)/);
  });
});
