import { env } from "cloudflare:test";
import { Hono } from "hono";
import { beforeEach, describe, expect, it } from "vitest";
import { siteAuth } from "../src/middleware/auth";
import type { AppEnv } from "../src/types";
import { activateTestSite, seedLicenseAndBucket } from "./helpers";

function protectedApp() {
  const a = new Hono<AppEnv>();
  a.use("*", siteAuth);
  a.get("/whoami", (c) => c.json({ site_id: c.get("site").id }));
  return a;
}

describe("siteAuth middleware", () => {
  beforeEach(seedLicenseAndBucket);

  it("rejects missing and malformed tokens with 401", async () => {
    const a = protectedApp();
    expect((await a.request("/whoami", {}, env)).status).toBe(401);
    const bad = await a.request(
      "/whoami",
      { headers: { authorization: "Bearer not.a.jwt" } },
      env,
    );
    expect(bad.status).toBe(401);
  });

  it("accepts a fresh token and exposes the site", async () => {
    const { site_id, site_token } = await activateTestSite();
    const res = await protectedApp().request(
      "/whoami",
      { headers: { authorization: `Bearer ${site_token}` } },
      env,
    );
    expect(res.status).toBe(200);
    expect(await res.json()).toEqual({ site_id });
  });

  it("rejects a token from a previous token_version after re-activation", async () => {
    const first = await activateTestSite();
    await activateTestSite(); // rotation: token_version -> 2
    const res = await protectedApp().request(
      "/whoami",
      { headers: { authorization: `Bearer ${first.site_token}` } },
      env,
    );
    expect(res.status).toBe(401);
  });
});
