import { createBullBoard } from "@bull-board/api";
import { BullMQAdapter } from "@bull-board/api/bullMQAdapter";
import { HonoAdapter } from "@bull-board/hono";
import { serveStatic } from "@hono/node-server/serve-static";
import { Hono } from "hono";
import { handle } from "hono/vercel";
import { getQuoteRpaQueue } from "@/workers/rpa/queue";

const BASE_PATH = "/api/admin/queues";

let honoHandler: ((request: Request) => Response | Promise<Response>) | null =
  null;

function createHandler() {
  const serverAdapter = new HonoAdapter(serveStatic);

  createBullBoard({
    queues: [
      new BullMQAdapter(getQuoteRpaQueue(), {
        readOnlyMode: false,
        allowRetries: true,
      }),
    ],
    serverAdapter,
    options: {
      uiConfig: {
        boardTitle: "报价 RPA 队列监控",
      },
    },
  });

  serverAdapter.setBasePath(BASE_PATH);

  const app = new Hono().basePath("/api");
  app.route("/admin/queues", serverAdapter.registerPlugin());

  return handle(app);
}

export function getBullBoardHandler() {
  if (!honoHandler) {
    honoHandler = createHandler();
  }
  return honoHandler;
}
