import type { Request, Response, NextFunction } from 'express';
import { errorResponse } from '../utils/response.js';

// Use after `verifyFirebaseToken`. With no roles given, it only checks that a
// valid user is attached; with roles given, the user's role must be one of them.
export default function authorize(...roles: string[]) {
  return (req: Request, res: Response, next: NextFunction) => {
    if (!req.user) return void errorResponse(res, 'Authentication required', 401);
    if (roles.length && !roles.includes(req.user.role)) {
      return void errorResponse(res, 'Insufficient permissions', 403);
    }
    next();
  };
}
