/**
 * Assigns a correlation id to every request and echoes it on the response.
 * Honours an inbound `x-request-id` so a trace survives a proxy hop.
 */
import { randomUUID } from 'node:crypto';
import type { NextFunction, Request, Response } from 'express';

export function requestId(req: Request, res: Response, next: NextFunction): void {
  const inbound = req.get('x-request-id');
  req.id = inbound && inbound.length <= 128 ? inbound : randomUUID();
  res.setHeader('x-request-id', req.id);
  next();
}
