import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';

export interface ErrorResponse {
  error: string;
  message: string;
  statusCode: number;
  code?: string;
  details?: Record<string, unknown>;
  timestamp: string;
  path: string;
}

export async function errorHandlingMiddleware(fastify: FastifyInstance) {
  // Custom error handler
  fastify.setErrorHandler((error, request: FastifyRequest, reply: FastifyReply) => {
    const response: ErrorResponse = {
      error: error.name || 'Internal Server Error',
      message: error.message || 'An unexpected error occurred',
      statusCode: error.statusCode || 500,
      code: (error as any).code,
      timestamp: new Date().toISOString(),
      path: request.url,
    };

    // Log error
    fastify.log.error({
      error: response,
      stack: error.stack,
      method: request.method,
      userAgent: request.headers['user-agent'],
    });

    // Send standardized error response
    reply.status(response.statusCode).send(response);
  });

  // 404 handler
  fastify.setNotFoundHandler((request: FastifyRequest, reply: FastifyReply) => {
    reply.status(404).send({
      error: 'Not Found',
      message: `Route ${request.method} ${request.url} not found`,
      statusCode: 404,
      timestamp: new Date().toISOString(),
      path: request.url,
    });
  });

  // Validation error handler
  fastify.addHook('onError', async (request: FastifyRequest, reply: FastifyReply, error) => {
    if (error.validation) {
      reply.status(400).send({
        error: 'Validation Error',
        message: 'Request validation failed',
        statusCode: 400,
        code: 'VALIDATION_ERROR',
        details: error.validation,
        timestamp: new Date().toISOString(),
        path: request.url,
      });
    }
  });
}
