import { afterEach, describe, expect, it } from "vitest";
import { verifyCronSecret } from "./cron-auth.js";

describe("verifyCronSecret — fail-closed when CRON_SECRET missing", () => {
  const original = process.env["CRON_SECRET"];

  afterEach(() => {
    if (original === undefined) delete process.env["CRON_SECRET"];
    else process.env["CRON_SECRET"] = original;
  });

  it("returns 401 when CRON_SECRET is unset", async () => {
    delete process.env["CRON_SECRET"];
    const req = new Request("http://localhost/api/cron/x", {
      headers: { Authorization: "Bearer whatever" },
    });
    const res = verifyCronSecret(req);
    expect(res).not.toBeNull();
    expect(res?.status).toBe(401);
  });

  it("returns 401 when CRON_SECRET is empty string", async () => {
    process.env["CRON_SECRET"] = "";
    const req = new Request("http://localhost/api/cron/x", {
      headers: { Authorization: "Bearer whatever" },
    });
    const res = verifyCronSecret(req);
    expect(res).not.toBeNull();
    expect(res?.status).toBe(401);
  });

  it("returns 401 when Authorization header is missing", () => {
    process.env["CRON_SECRET"] = "real-secret";
    const req = new Request("http://localhost/api/cron/x");
    const res = verifyCronSecret(req);
    expect(res?.status).toBe(401);
  });

  it("returns 401 when Authorization header mismatches", () => {
    process.env["CRON_SECRET"] = "real-secret";
    const req = new Request("http://localhost/api/cron/x", {
      headers: { Authorization: "Bearer wrong-secret" },
    });
    const res = verifyCronSecret(req);
    expect(res?.status).toBe(401);
  });

  it("returns null (allow) when Authorization header matches", () => {
    process.env["CRON_SECRET"] = "real-secret";
    const req = new Request("http://localhost/api/cron/x", {
      headers: { Authorization: "Bearer real-secret" },
    });
    expect(verifyCronSecret(req)).toBeNull();
  });
});
