/**
 * Common middleware utilities
 */

import { FastifyInstance, FastifyRequest } from 'fastify';
import { randomUUID } from 'crypto';

/**
 * Add correlation ID middleware
 */
export function addCorrelationId(server: FastifyInstance): void {
  server.addHook('onRequest', async (request: FastifyRequest, reply) => {
    const correlationId =
      (request.headers['x-request-id'] as string) || randomUUID();
    request.id = correlationId;
    reply.header('x-request-id', correlationId);
  });
}

/**
 * Add request logging middleware
 */
export function addRequestLogging(server: FastifyInstance): void {
  server.addHook('onRequest', async (request: FastifyRequest) => {
    request.log.info({
      method: request.method,
      url: request.url,
      ip: request.ip,
      userAgent: request.headers['user-agent'],
    });
  });

  server.addHook('onResponse', async (request: FastifyRequest, reply) => {
    request.log.info({
      method: request.method,
      url: request.url,
      statusCode: reply.statusCode,
      responseTime: reply.getResponseTime(),
    });
  });
}

