import { describe, expect, it } from "vitest";
import { createConfig } from "../../config.js";
import { MiddlewareManager } from "../../middlewares/middleware.js";
import { getMainRouter } from "../../routers/index.js";
import { createSignedAdminToken } from "../helpers/adminTokenTestUtils.js";

const ADMIN_TOKEN_SIGNING_SECRET = "admin-test-secret";
const ADMIN_TOKEN_AUDIENCE = "xtablo-admin";

describe("Admin Auth Middleware", () => {
  process.env.ADMIN_TOKEN_SIGNING_SECRET = ADMIN_TOKEN_SIGNING_SECRET;
  process.env.ADMIN_TOKEN_AUDIENCE = ADMIN_TOKEN_AUDIENCE;
  process.env.ADMIN_APP_URL = "http://localhost:5176";

  const config = createConfig();
  MiddlewareManager.initialize(config);
  const app = getMainRouter(config);

  it("rejects admin routes without an admin session", async () => {
    const res = await app.request("/admin/tables/profiles");

    expect(res.status).toBe(401);
    await expect(res.json()).resolves.toMatchObject({
      error: "Admin session required",
      code: "ADMIN_SESSION_REQUIRED",
    });
  });

  it("returns the current admin session for a valid admin session token", async () => {
    const sessionToken = createSignedAdminToken(
      {
        aud: ADMIN_TOKEN_AUDIENCE,
        email: "ops@xtablo.com",
        exp: Math.floor(Date.now() / 1000) + 900,
        role: "operator",
        sub: "operator-1",
        type: "admin_session",
      },
      ADMIN_TOKEN_SIGNING_SECRET
    );

    const res = await app.request("/admin/auth/session", {
      headers: {
        Authorization: `Bearer ${sessionToken}`,
      },
    });

    expect(res.status).toBe(200);
    await expect(res.json()).resolves.toMatchObject({
      role: "operator",
      operatorEmail: "ops@xtablo.com",
      operatorId: "operator-1",
    });
  });
});
