import { Request, Response, NextFunction } from 'express';
import { ROLES } from '../config/constants.js';
import logger from '../utils/logger.js';
import { AuthenticatedRequest } from '../../types/express.types.js';

/**
 * Role-based access control middleware
 * @param allowedRoles - Array of roles that can access the route
 * @returns Express middleware function
 */
export const checkRole = (allowedRoles: string[]) => {
    return (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
        try {
            // Check if user is authenticated
            if (!req.user) {
                return res.status(401).json({
                    success: false,
                    message: 'Authentication required'
                });
            }

            // Check if user role is in allowed roles
            if (!allowedRoles.includes(req.user.roleCode)) {
                logger.warn(`Access denied for user ${req.user.email} (${req.user.roleCode}) to route ${req.path}`);

                return res.status(403).json({
                    success: false,
                    message: 'Access denied. Insufficient permissions.',
                    requiredRoles: allowedRoles,
                    yourRole: req.user.roleCode
                });
            }

            // User has required role, proceed
            next();
        } catch (error) {
            logger.error('Role check error:', error);
            res.status(500).json({
                success: false,
                message: 'Authorization check failed'
            });
        }
    };
};

export { ROLES };
