/**
 * @copyright 2026 NHCarrigan
 * @license Naomi's Public License
 * @author Naomi Carrigan
 */

import { FastifyReply, FastifyRequest } from "fastify";
import { UserService } from "../services/user.service";

const userService = new UserService();

/**
 * Middleware to check if the authenticated user is an admin.
 * Must be used after app.authenticate.
 * Always checks the database to ensure admin status is current.
 */
export async function adminGuard(
  request: FastifyRequest,
  reply: FastifyReply
): Promise<void> {
  const user = request.user as { id: string };

  if (!user?.id) {
    return reply.code(401).send({ error: "Unauthorized" });
  }

  const dbUser = await userService.getUserById(user.id);
  if (!dbUser?.isAdmin) {
    return reply.code(403).send({ error: "Forbidden: Admin access required" });
  }
}