import crypto from "crypto";
import type { Request, Response, NextFunction } from "express";

const HEADER = "X-Request-Id";

/**
 * Assigns a unique request ID to every incoming request.
 * If the client (or a reverse proxy) already sent X-Request-Id, reuse it;
 * otherwise generate a short random hex string.
 * The ID is stored on `res.locals.requestId` for downstream middleware/routes
 * and echoed back via the X-Request-Id response header.
 */
export function requestIdMiddleware(req: Request, res: Response, next: NextFunction): void {
  const id = (req.headers[HEADER.toLowerCase()] as string | undefined) ?? crypto.randomUUID();
  res.locals["requestId"] = id;
  res.setHeader(HEADER, id);
  next();
}
