import { Response, NextFunction } from 'express';
import db from '../../database/models/index.js';
import { AuthRequest } from '../../types/express.types.js';

/**
 * Middleware to check if the user has the correct role for the current approval level of an LOI/LOA request.
 */
export const checkApprovalPermission = (type: 'LOI' | 'LOA') => {
    return async (req: AuthRequest, res: Response, next: NextFunction) => {
        try {
            const { requestId } = req.params;
            const model = type === 'LOI' ? db.LoiApproval : db.LoaApproval;

            // Find current pending approval level
            const currentApproval = await model.findOne({
                where: { requestId, action: 'Pending' },
                order: [['level', 'ASC']]
            });

            if (!currentApproval) {
                return res.status(404).json({ success: false, message: `No pending ${type} approval found` });
            }

            // Check if user's role matches the required role for this level
            if (req.user?.roleCode !== currentApproval.approverRole && req.user?.roleCode !== 'Super Admin') {
                return res.status(403).json({
                    success: false,
                    message: `Permission denied. Only ${currentApproval.approverRole} can perform this action at Level ${currentApproval.level}.`
                });
            }

            next();
        } catch (error) {
            console.error('Approval permission check error:', error);
            res.status(500).json({ success: false, message: 'Internal server error during permission check' });
        }
    };
};

/**
 * Middleware to check if the user has the correct role for a specific application stage.
 */
export const checkStagePermission = (allowedRoles: string[]) => {
    return async (req: AuthRequest, res: Response, next: NextFunction) => {
        try {
            if (!req.user) return res.status(401).json({ success: false, message: 'Unauthorized' });

            if (!allowedRoles.includes(req.user.roleCode) && req.user.roleCode !== 'Super Admin') {
                return res.status(403).json({
                    success: false,
                    message: 'Access denied for this stage action',
                    requiredRoles: allowedRoles
                });
            }

            next();
        } catch (error) {
            res.status(500).json({ success: false, message: 'Stage permission check failed' });
        }
    };
};
