import { parseAdminAuth } from "@/lib/api/admin-auth-context";
import { getBullBoardHandler } from "@/lib/bull-board/setup";
import { fail } from "@/lib/response";
import { AuthError } from "@/modules/auth/errors";

export const dynamic = "force-dynamic";

type RouteContext = { params: Promise<{ slug?: string[] }> };

async function guardAdmin(request: Request): Promise<Response | null> {
  try {
    parseAdminAuth(request);
    return null;
  } catch (error) {
    if (error instanceof AuthError) {
      return fail(error.code, error.message, error.httpStatus);
    }
    throw error;
  }
}

async function dispatch(request: Request) {
  const denied = await guardAdmin(request);
  if (denied) {
    return denied;
  }
  return getBullBoardHandler()(request);
}

export async function GET(request: Request, _ctx: RouteContext) {
  return dispatch(request);
}

export async function POST(request: Request, _ctx: RouteContext) {
  return dispatch(request);
}

export async function PUT(request: Request, _ctx: RouteContext) {
  return dispatch(request);
}

export async function DELETE(request: Request, _ctx: RouteContext) {
  return dispatch(request);
}

export async function PATCH(request: Request, _ctx: RouteContext) {
  return dispatch(request);
}
