import { logger } from '@goodgo/logger';
import { Request, Response, NextFunction } from 'express';

import { rbacService } from '../modules/rbac/rbac.service';

/**
 * EN: RBAC middleware factory
 * VI: Factory middleware RBAC
 */
export const requirePermission = (
  resource: string,
  action: string,
  scope?: string
) => {
  return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const userId = (req as any).user?.id || (req as any).user?.sub;

      if (!userId) {
        res.status(401).json({
          success: false,
          error: {
            code: 'UNAUTHORIZED',
            message: 'Authentication required',
          },
        });
        return;
      }

      const hasPermission = await rbacService.hasPermission(
        userId,
        resource,
        action,
        scope
      );

      if (!hasPermission) {
        res.status(403).json({
          success: false,
          error: {
            code: 'INSUFFICIENT_PERMISSIONS',
            message: `Requires ${action} permission on ${resource}`,
          },
        });
        return;
      }

      next();
    } catch (error) {
      logger.error('RBAC middleware error', { error });
      res.status(500).json({
        success: false,
        error: {
          code: 'INTERNAL_ERROR',
          message: 'Permission check failed',
        },
      });
    }
  };
};
