import type { Request, Response, NextFunction } from 'express';
import * as roleModel from '../models/role.model.js';
import { errorResponse } from '../utils/response.js';

// Use after `verifyFirebaseToken`, alongside or instead of `authorize(...)`.
// Checks the user's role actually has this specific permission (via
// role_permissions) — finer-grained than authorize(), which only checks the
// role's name. Requires the permission to be seeded and assigned to the role
// first (see prisma/seed.ts) — an empty role_permissions table means every
// check here fails, so don't gate an existing route with this until its
// permission is actually seeded and assigned.
export default function requirePermission(permissionName: string) {
  return async (req: Request, res: Response, next: NextFunction) => {
    if (!req.user) return void errorResponse(res, 'Authentication required', 401);
    try {
      const allowed = await roleModel.roleHasPermission(req.user.role, permissionName);
      if (!allowed) return void errorResponse(res, 'Insufficient permissions', 403);
      next();
    } catch (error) {
      next(error);
    }
  };
}
