import { describe, test } from "node:test";
import assert from "node:assert/strict";

import type { NextConfig } from "next";

// Loaded at runtime by path (Node strips the types); tsc does not allow a `.ts` import specifier.
const configPath = "../next.config.ts";
const nextConfig = ((await import(configPath)) as { default: NextConfig }).default;

/** S-PLA-1 — platform headers: no framework banner, CSP follows the API origin. */
describe("S-PLA-1 — next.config platform headers", () => {
  test("the x-powered-by banner is disabled", () => {
    assert.equal(nextConfig.poweredByHeader, false);
  });

  test("every route carries the CSP with the API origin in connect-src and frame-src", async () => {
    const rules = await nextConfig.headers!();
    const all = rules.find((rule) => rule.source === "/(.*)");
    assert.ok(all, "catch-all header rule");
    const csp = all.headers.find((h) => h.key === "Content-Security-Policy")?.value ?? "";
    const origin = new URL(process.env.NEXT_PUBLIC_BACKEND_URL?.trim() || "https://portal.fursa.raiyan.cc/api").origin;
    assert.match(csp, new RegExp(`connect-src 'self' ${origin.replace(/\./g, "\\.")}`));
    assert.match(csp, new RegExp(`frame-src https://accounts\\.google\\.com ${origin.replace(/\./g, "\\.")}`));
    assert.match(csp, /form-action 'self'/);
    assert.match(csp, /object-src 'none'/);
    for (const key of ["X-Content-Type-Options", "Referrer-Policy", "X-Frame-Options", "Permissions-Policy"]) {
      assert.ok(all.headers.some((h) => h.key === key), key);
    }
  });

  test("the legacy development list keeps its permanent redirect", async () => {
    const redirects = await nextConfig.redirects!();
    assert.deepEqual(redirects.find((r) => r.source === "/learn-and-share-list"), {
      source: "/learn-and-share-list",
      destination: "/development-opportunities-list",
      permanent: true,
    });
  });
});
