/**
 * @ai-summary Fastify request logging plugin with correlation IDs
 * @ai-context Logs request/response details with timing and requestId
 */
import { FastifyPluginAsync } from 'fastify';
import fp from 'fastify-plugin';
import { randomUUID } from 'crypto';
import { logger } from '../logging/logger';

const loggingPlugin: FastifyPluginAsync = async (fastify) => {
  fastify.addHook('onRequest', async (request) => {
    request.startTime = Date.now();
    // Extract X-Request-Id from Traefik or generate new UUID
    request.requestId = (request.headers['x-request-id'] as string) || randomUUID();
  });

  fastify.addHook('onResponse', async (request, reply) => {
    const duration = Date.now() - (request.startTime || Date.now());

    logger.info('Request processed', {
      requestId: request.requestId,
      method: request.method,
      path: request.url,
      status: reply.statusCode,
      duration,
      ip: request.ip,
    });
  });
};

declare module 'fastify' {
  interface FastifyRequest {
    startTime?: number;
    requestId?: string;
  }
}

export default fp(loggingPlugin, {
  name: 'logging-plugin'
});
