/**
 * TLS Enforcement Middleware for SentryAgent.ai AgentIdP.
 *
 * SOC 2 CC6.7 — Ensures all inbound HTTP connections are upgraded to HTTPS.
 * In production, any request arriving without the `x-forwarded-proto: https`
 * header (set by the load balancer / reverse proxy) is redirected to the
 * equivalent HTTPS URL with a 301 Moved Permanently response.
 *
 * In non-production environments (development, test, staging with local TLS),
 * the middleware is a no-op to preserve developer ergonomics.
 */

import { Request, Response, NextFunction, RequestHandler } from 'express';

/**
 * Express middleware that enforces HTTPS connections in production.
 *
 * Behaviour in `production` (`NODE_ENV === 'production'`):
 *   - Reads the `X-Forwarded-Proto` header (set by the upstream load balancer).
 *   - If the value is not `https`, responds with HTTP 301 to `https://{host}{url}`.
 *   - If the value is `https`, passes through to the next middleware.
 *
 * Behaviour in all other environments:
 *   - Always calls `next()` immediately — no redirect, no overhead.
 *
 * @param req - Express request.
 * @param res - Express response.
 * @param next - Express next function.
 */
export const tlsEnforcementMiddleware: RequestHandler = (
  req: Request,
  res: Response,
  next: NextFunction,
): void => {
  if (process.env['NODE_ENV'] !== 'production') {
    next();
    return;
  }

  const proto = req.headers['x-forwarded-proto'];
  if (proto !== 'https') {
    const httpsUrl = `https://${req.headers['host'] ?? ''}${req.url}`;
    res.redirect(301, httpsUrl);
    return;
  }

  next();
};
