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 Router", () => {
  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 requests without a valid privileged token", async () => {
    const res = await app.request("/admin/auth/exchange", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ accessToken: "bad-token" }),
    });

    expect(res.status).toBe(401);
    await expect(res.json()).resolves.toMatchObject({
      error: "Invalid privileged access token",
      code: "INVALID_ADMIN_ACCESS_TOKEN",
    });
  });

  it("exchanges a valid privileged token for an admin session", async () => {
    const accessToken = createSignedAdminToken(
      {
        aud: ADMIN_TOKEN_AUDIENCE,
        email: "ops@xtablo.com",
        exp: Math.floor(Date.now() / 1000) + 3600,
        role: "operator",
        sub: "operator-1",
        type: "admin_access",
      },
      ADMIN_TOKEN_SIGNING_SECRET
    );

    const res = await app.request("/admin/auth/exchange", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ accessToken }),
    });

    expect(res.status).toBe(200);
    await expect(res.json()).resolves.toMatchObject({
      role: "operator",
      operatorEmail: "ops@xtablo.com",
      sessionToken: expect.any(String),
      expiresAt: expect.any(String),
    });
  });
});
