import { randomUUID } from 'crypto';

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

import { incrementMetric } from '../observability/metrics';

export const requestContext = (req: Request, res: Response, next: NextFunction): void => {
  const requestId = req.headers['x-request-id']?.toString() ?? randomUUID();
  const start = Date.now();

  res.setHeader('x-request-id', requestId);
  incrementMetric('http.requests.total');

  res.on('finish', () => {
    const durationMs = Date.now() - start;
    incrementMetric(`http.status.${res.statusCode}`);

    console.log(
      JSON.stringify({
        requestId,
        method: req.method,
        path: req.path,
        statusCode: res.statusCode,
        durationMs,
        ip: req.ip,
      }),
    );
  });

  next();
};
