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 Datasets 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 datasets", async () => {
    const res = await app.request("/admin/datasets", {
      headers: {
        Authorization: `Bearer ${sessionToken}`,
      },
    });

    expect(res.status).toBe(200);
    await expect(res.json()).resolves.toMatchObject({
      datasets: expect.arrayContaining([
        expect.objectContaining({
          id: "profile_growth",
          label: "User Growth",
        }),
      ]),
    });
  });

  it("returns chart-ready data for a registered dataset", async () => {
    const res = await app.request("/admin/datasets/plan_mix", {
      headers: {
        Authorization: `Bearer ${sessionToken}`,
      },
    });

    expect(res.status).toBe(200);
    await expect(res.json()).resolves.toMatchObject({
      chartType: "donut",
      id: "plan_mix",
      metricLabel: "Users",
      points: expect.any(Array),
    });
  });
});
