import crypto from 'crypto'
import type { Request, Response, NextFunction } from 'express'

export function requestIdMiddleware(req: Request, res: Response, next: NextFunction) {
  const incoming = req.headers['x-request-id']
  const requestId = Array.isArray(incoming) ? incoming[0] : incoming
  req.requestId = requestId && requestId.length <= 128 ? requestId : `req_${crypto.randomUUID()}`
  res.setHeader('X-Request-Id', req.requestId)
  next()
}
