import { beforeEach, describe, expect, it, vi } from "vitest";
import { GET as getQueueStats } from "@/app/api/admin/queues/stats/route";
import { GET as getBullBoard } from "@/app/api/admin/queues/[[...slug]]/route";

vi.mock("@/workers/rpa/queue", () => ({
  getQuoteRpaQueue: vi.fn(),
  getQuoteRpaQueueCounts: vi.fn().mockResolvedValue({
    waiting: 2,
    active: 1,
    delayed: 3,
    failed: 4,
    completed: 100,
  }),
}));

vi.mock("@/lib/bull-board/setup", () => ({
  getBullBoardHandler: vi.fn(() => async () =>
    new Response("<html>Bull Board</html>", {
      status: 200,
      headers: { "Content-Type": "text/html" },
    }),
  ),
}));

const ADMIN_HEADERS = {
  "x-auth-type": "admin",
  "x-user-id": "U_admin_demo",
  "x-user-role": "admin",
};

const SERVICE_HEADERS = {
  "x-auth-type": "service",
  "x-customer-id": "CUST_001",
  "x-permissions": "",
};

beforeEach(() => {
  vi.clearAllMocks();
});

describe("admin queues API（task-132）", () => {
  it("GET /api/admin/queues/stats → 200 + counts", async () => {
    const response = await getQueueStats(
      new Request("http://localhost/api/admin/queues/stats", {
        headers: ADMIN_HEADERS,
      }),
    );
    const json = await response.json();

    expect(response.status).toBe(200);
    expect(json.code).toBe(0);
    expect(json.data.queue_name).toBe("quote-rpa");
    expect(json.data.depth).toBe(6);
    expect(json.data.failed).toBe(4);
    expect(json.data.delayed).toBe(3);
  });

  it("GET /api/admin/queues/stats 非 admin → 403", async () => {
    const response = await getQueueStats(
      new Request("http://localhost/api/admin/queues/stats", {
        headers: SERVICE_HEADERS,
      }),
    );
    const json = await response.json();

    expect(response.status).toBe(403);
    expect(json.code).toBe("FORBIDDEN");
  });

  it("GET /api/admin/queues Bull Board admin → 200 HTML", async () => {
    const response = await getBullBoard(
      new Request("http://localhost/api/admin/queues", {
        headers: ADMIN_HEADERS,
      }),
      { params: Promise.resolve({}) },
    );

    expect(response.status).toBe(200);
    expect(await response.text()).toContain("Bull Board");
  });

  it("GET /api/admin/queues 非 admin → 403", async () => {
    const response = await getBullBoard(
      new Request("http://localhost/api/admin/queues", {
        headers: SERVICE_HEADERS,
      }),
      { params: Promise.resolve({}) },
    );
    const json = await response.json();

    expect(response.status).toBe(403);
    expect(json.code).toBe("FORBIDDEN");
  });
});
