import { randomUUID } from 'node:crypto';
import type { Request, Response, NextFunction } from 'express';

// Lets a client (or a gateway in front of us) supply its own correlation id;
// otherwise generates one. Echoed back in the response header and included
// in every log line for this request, so one request is traceable end to end.
export default function requestId(req: Request, res: Response, next: NextFunction) {
  const incoming = req.headers['x-request-id'];
  const id = typeof incoming === 'string' && incoming.trim() ? incoming : randomUUID();
  req.id = id;
  res.setHeader('X-Request-Id', id);
  next();
}
