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 Actions 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);

  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
  );

  it("lists curated admin actions", async () => {
    const res = await app.request("/admin/actions", {
      headers: {
        Authorization: `Bearer ${sessionToken}`,
      },
    });

    expect(res.status).toBe(200);
    await expect(res.json()).resolves.toMatchObject({
      actions: expect.arrayContaining([
        expect.objectContaining({
          id: "deactivate_tablo_access",
          label: "Deactivate Tablo Access",
        }),
      ]),
    });
  });

  it("validates required input before running an action", async () => {
    const res = await app.request("/admin/actions/deactivate_tablo_access/run", {
      body: JSON.stringify({ tabloId: "tablo-1" }),
      headers: {
        Authorization: `Bearer ${sessionToken}`,
        "Content-Type": "application/json",
      },
      method: "POST",
    });

    expect(res.status).toBe(400);
    await expect(res.json()).resolves.toMatchObject({
      error: "tabloId, userId, and reason are required",
    });
  });
});
