import type { NextRequest } from "next/server";
import { getToken } from "next-auth/jwt";
import { HttpError } from "@/server/http/errors";

const NEXTAUTH_SECRET = process.env.NEXTAUTH_SECRET;

/**
 * Verifies that the request is authenticated with an admin role.
 * Throws HttpError if not authenticated or not an admin.
 * 
 * @param request - The incoming request
 * @returns The JWT token with admin role
 * @throws HttpError with status 401 if not authenticated or not admin
 */
export async function requireAdmin(request: Request | NextRequest) {
  if (!NEXTAUTH_SECRET) {
    throw new HttpError("Authentication not configured", { status: 500 });
  }

  const token = await getToken({ 
    req: request as NextRequest, 
    secret: NEXTAUTH_SECRET 
  });

  if (!token || (token as any).role !== "admin") {
    throw new HttpError("Unauthorized", { status: 401 });
  }

  return token;
}


