import { describe, expect, test } from "vitest";

import { requireApiAccess } from "../auth";

describe("requireApiAccess", () => {
  test("allows local test requests when auth is explicitly disabled", () => {
    const request = new Request("http://localhost/api/jobs");

    const result = requireApiAccess(request, {
      apiAccessKey: undefined,
      authDisabled: true,
    });

    expect(result.ok).toBe(true);
  });

  test("rejects requests when the configured key is missing", () => {
    const request = new Request("http://localhost/api/jobs");

    const result = requireApiAccess(request, {
      apiAccessKey: "secret",
      authDisabled: false,
    });

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.response.status).toBe(401);
    }
  });

  test("rejects requests with the wrong key", () => {
    const request = new Request("http://localhost/api/jobs", {
      headers: { "x-api-key": "wrong" },
    });

    const result = requireApiAccess(request, {
      apiAccessKey: "secret",
      authDisabled: false,
    });

    expect(result.ok).toBe(false);
  });

  test("allows requests with the correct key", () => {
    const request = new Request("http://localhost/api/jobs", {
      headers: { "x-api-key": "secret" },
    });

    const result = requireApiAccess(request, {
      apiAccessKey: "secret",
      authDisabled: false,
    });

    expect(result.ok).toBe(true);
  });
});
