import type { FastifyRequest, FastifyReply } from 'fastify';
import type { RbacService, RbacAction } from '../services/rbac.service.js';

export function createRbacMiddleware(rbacService: RbacService) {
  function requirePermission(resource: string, action: RbacAction, resourceName?: string) {
    return async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {
      if (request.userId === undefined) {
        reply.code(401).send({ error: 'Authentication required' });
        return;
      }

      const allowed = await rbacService.canAccess(request.userId, action, resource, resourceName);
      if (!allowed) {
        reply.code(403).send({ error: 'Forbidden' });
        return;
      }
    };
  }

  function requireOperation(operation: string) {
    return async (request: FastifyRequest, reply: FastifyReply): Promise<void> => {
      if (request.userId === undefined) {
        reply.code(401).send({ error: 'Authentication required' });
        return;
      }

      const allowed = await rbacService.canRunOperation(request.userId, operation);
      if (!allowed) {
        reply.code(403).send({ error: 'Forbidden' });
        return;
      }
    };
  }

  return { requirePermission, requireOperation };
}
