import { describe, test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { liveOpportunityStatus } from "@/features/opportunities/certificatesOutdated";
import { sendCertificatesBlockedReason } from "@/features/opportunities/learnServeCertificates";

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

describe("S-CER-1 development list: «إرسال الشهادات» gates on the live resolved status, not the stashed snapshot", () => {
  test("the live detail's status wins over a snapshot taken before the end", () => {
    assert.equal(liveOpportunityStatus({ opportunity_status: "completed" }, "active"), "completed");
    // Until the detail loads, the snapshot is all there is.
    assert.equal(liveOpportunityStatus(undefined, "active"), "active");
    assert.equal(liveOpportunityStatus({ opportunity_status: null }, "completed"), "completed");
    assert.equal(liveOpportunityStatus(null, undefined), null);
  });

  test("a stale «active» snapshot no longer blocks send once the server resolved «completed»", () => {
    const attendance = { anyAttended: true, certain: true };
    assert.equal(sendCertificatesBlockedReason("active", attendance), "not-ended");
    assert.equal(sendCertificatesBlockedReason(liveOpportunityStatus({ opportunity_status: "completed" }, "active"), attendance), null);
  });

  test("the list and the hook are wired to it", () => {
    const list = src("features/opportunities/components/RegisterListForLearnandServe.tsx");
    assert.match(list, /useCertificatesOutdated\("learn-serve", opportunityId, navState\?\.opportunity_status\)/);
    assert.match(list, /sendCertificatesBlockedReason\(\s*certificates\.opportunityStatus,/);
    assert.match(src("features/opportunities/components/useCertificatesOutdated.ts"), /opportunityStatus: liveOpportunityStatus\(source, stashedStatus\)/);
  });
});

describe("S-CER-2 volunteer list: the send hint follows the computed end, not the stashed status", () => {
  test("«available after the end» is keyed on opportunityEnded", () => {
    const list = src("features/opportunities/components/VolunteerList.tsx");
    assert.match(list, /!screen\.opportunityEnded\s*\?\s*screen\.t\("COMMON\.CERTIFICATES_AFTER_END"\)/);
    assert.doesNotMatch(list, /opportunity_status !== "completed"/);
  });
});
