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

import { zeroTrustValidator } from '../core/security/zero-trust.validator';

/**
 * EN: Zero-Trust middleware for request validation
 * VI: Middleware Zero-Trust cho xác thực request
 */
export const zeroTrustMiddleware = async (
  req: Request,
  res: Response,
  next: NextFunction
): Promise<void> => {
  try {
    // Skip zero-trust for health checks and public endpoints
    if (
      req.path.startsWith('/health') ||
      req.path.startsWith('/metrics') ||
      req.path.startsWith('/api-docs')
    ) {
      return next();
    }

    const result = await zeroTrustValidator.validateRequest(req);

    if (!result.allowed) {
      if (result.requireMFA) {
        res.status(403).json({
          success: false,
          error: {
            code: 'MFA_REQUIRED',
            message: 'Multi-factor authentication required',
            riskScore: result.riskScore,
          },
        });
        return;
      }

      res.status(403).json({
        success: false,
        error: {
          code: 'ACCESS_DENIED',
          message: 'Access denied due to security policy',
          reasons: result.reasons,
        },
      });
      return;
    }

    // Attach risk score to request for logging
    (req as any).riskScore = result.riskScore;
    next();
  } catch (error) {
    logger.error('Zero-trust validation error', { error });
    // Fail secure: deny on error
    res.status(403).json({
      success: false,
      error: {
        code: 'VALIDATION_ERROR',
        message: 'Request validation failed',
      },
    });
  }
};
