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

const loggingPlugin: FastifyPluginAsync = async (fastify) => {
  fastify.addHook('onRequest', async (request) => {
    request.startTime = Date.now();
  });

  fastify.addHook('onResponse', async (request, reply) => {
    const duration = Date.now() - (request.startTime || Date.now());
    
    logger.info('Request processed', {
      method: request.method,
      path: request.url,
      status: reply.statusCode,
      duration,
      ip: request.ip,
    });
  });
};

// Augment FastifyRequest to include startTime
declare module 'fastify' {
  interface FastifyRequest {
    startTime?: number;
  }
}

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