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

/**
 * Middleware to reject requests from participants who have been revoked.
 * This should be placed AFTER the authenticate middleware.
 */
export const checkRevocation = async (req: AuthRequest, res: Response, next: NextFunction) => {
    try {
        const userId = req.user?.id;
        if (!userId) return next();

        // BYPASS: Super Admin and other National administrative roles should always have access
        const nationalRoles = ['NBH', 'DD Head', 'DD Lead', 'Finance', 'DD Admin', 'Legal Admin', 'Super Admin', 'Admin', 'CEO', 'CCO'];
        if (nationalRoles.includes(req.user?.roleCode || '')) {
            return next();
        }

        // Try to identify requestId and requestType from various sources with safe navigation
        const requestId = req.params?.requestId || req.params?.id || req.body?.requestId || req.query?.requestId;
        const requestType = req.params?.requestType || req.body?.requestType || req.query?.requestType || 'application';

        // If we can't identify the request context, we can't check revocation here
        if (!requestId) return next();

        const participant = await RequestParticipant.findOne({
            where: {
                requestId,
                userId,
                // If requestType is provided, include it in filter
                ...(requestType && { requestType })
            }
        });

        // If user is a participant and has a revokedAt timestamp, block them
        if (participant && participant.metadata && participant.metadata.revokedAt) {
            console.warn(`[Revocation] User ${userId} blocked from ${req.method} ${req.path} for request ${requestId}`);
            return res.status(403).json({
                success: false,
                message: 'Your access to this request has been revoked. You can no longer perform any actions or post messages.',
                revoked: true
            });
        }

        next();
    } catch (error) {
        console.error('Revocation check middleware error:', error);
        next(); // Fail open for safety, but log error
    }
};
