import { Request, Response, NextFunction } from 'express';
import { logger } from '../../utils/logger';

/**
 * [CORE_SEC_07] 全链路 mTLS 强制加密守卫
 * @description 校验请求是否携带合法的客户端证书。在生产环境下，由 Nginx/ALB 负责终止 mTLS 并通过 Header 传递证书信息。
 */
export const mtlsGuard = (req: Request, res: Response, next: NextFunction) => {
  // 1. 获取证书指纹或序列号 (假设由反向代理通过 Header 传递)
  const certFingerprint = req.header('X-Client-Cert-Fingerprint');
  const certSubject = req.header('X-Client-Cert-Subject');

  // 2. 如果是开发环境且未配置 mTLS，则跳过 (可选)
  if (process.env.NODE_ENV === 'development' && !process.env.STRICT_MTLS) {
    return next();
  }

  // 3. 校验指纹是否存在
  if (!certFingerprint) {
    logger.error(`[mTLS] Request blocked: Missing client certificate fingerprint. IP: ${req.ip}`);
    return res.status(403).json({
      success: false,
      error: 'mTLS_REQUIRED',
      message: 'Secure connection via client certificate is required.'
    });
  }

  // 4. 将证书信息挂载到请求上下文，供后续业务逻辑使用 (如 NodeIdentityService)
  (req as any).mtlsContext = {
    fingerprint: certFingerprint,
    subject: certSubject
  };

  logger.info(`[mTLS] Validated client certificate: ${certSubject} (${certFingerprint.substring(0, 8)}...)`);
  next();
};
