import * as Sentry from '@sentry/node';
import fp from 'fastify-plugin';
import { FastifyPluginAsync, FastifyRequest, FastifyReply } from 'fastify';

interface SentryPluginOptions {
  dsn?: string;
  environment?: string;
  debug?: boolean;
}

export const autoConfig = {
  // Set default options for the plugin
  dsn: process.env.SENTRY_DSN,
  environment: process.env.SENTRY_ENVIRONMENT || 'development',
  debug: false
};

const sentryPlugin: FastifyPluginAsync<SentryPluginOptions> = async (fastify, options) => {
  const {
    dsn = fastify.config?.SENTRY_DSN || process.env.SENTRY_DSN,
    environment = fastify.config?.SENTRY_ENVIRONMENT || process.env.SENTRY_ENVIRONMENT || 'development',
    debug = false
  } = options;

  if (!dsn) {
    fastify.log.warn('Sentry DSN not provided, skipping initialization');
    return;
  }

  // Initialize Sentry with minimal configuration
  Sentry.init({
    dsn,
    environment,
    debug
  });

  // Add Sentry error handler, but don't override the existing one
  const originalErrorHandler = fastify.errorHandler;
  fastify.setErrorHandler((error, request, reply) => {
    // Capture the exception with request details
    Sentry.captureException(error, {
      extra: {
        method: request.method,
        url: request.url,
        params: request.params,
        query: request.query,
        ip: request.ip
      }
    });

    if (originalErrorHandler) {
      return originalErrorHandler(error, request, reply);
    }

    reply.status(500).send({ error: 'Internal Server Error' });
  });

  // Add Sentry to fastify instance
  fastify.decorate('sentry', Sentry);

  // Log initialization success
  fastify.log.info(`Sentry initialized for environment: ${environment}`);
};

// Augment FastifyInstance to include sentry
declare module 'fastify' {
  interface FastifyInstance {
    sentry: typeof Sentry;
  }
}

export default fp(sentryPlugin, {
  name: 'fastify-sentry',
  fastify: '5.x'
}); 