import { randomUUID } from "node:crypto";
import { Request, Response, NextFunction } from "express";
import { env } from "../../config/env";

declare module "express-serve-static-core" {
  interface Request {
    requestId: string;
    traceId?: string;
  }
}

export function requestContext(req: Request, _res: Response, next: NextFunction) {
  const requestId =
    (req.header(env.TRACE_HEADER) as string | undefined) ||
    req.header("x-trace-id") ||
    randomUUID();

  const traceId =
    (req.header("x-trace-id") as string | undefined) || requestId;

  req.requestId = requestId;
  req.traceId = traceId;

  next();
}
