/**
 * @ai-summary Fastify global error handling plugin
 * @ai-context Handles uncaught errors with structured logging
 */
import { FastifyPluginAsync, FastifyError } from 'fastify';
import fp from 'fastify-plugin';
import { logger } from '../logging/logger';

const errorPlugin: FastifyPluginAsync = async (fastify) => {
  fastify.setErrorHandler((error: FastifyError, request, reply) => {
    logger.error('Unhandled error', {
      error: error.message,
      stack: error.stack,
      path: request.url,
      method: request.method,
    });

    reply.status(500).send({
      error: 'Internal server error',
    });
  });
};

export default fp(errorPlugin, {
  name: 'error-plugin'
});