import {FastifyPluginAsyncTypebox, Type} from '@fastify/type-provider-typebox'

const plugin: FastifyPluginAsyncTypebox = async (fastify) => {
  // Diagnostic endpoint for Sentry
  fastify.get('/api/sentry-diagnostics', {
    schema: {
      tags: ['Sentry'],
      description: 'Sentry diagnostics endpoint - tests Sentry configuration and connectivity',
      response: {
        200: Type.String()
      }
    }
  }, async (request, reply) => {
    let output = 'Sentry Diagnostics Report\n';
    output += '========================\n';
    output += `Timestamp: ${new Date().toISOString()}\n\n`;
    
    output += '## Sentry SDK Status\n';
    output += `Sentry Enabled: true\n`;
    output += `Environment: ${process.env.SENTRY_ENVIRONMENT || 'development'}\n\n`;
    
    output += '## Test Event\n';
    try {
      const eventId = fastify.sentry.captureMessage(`Diagnostics test from ${request.hostname} at ${new Date().toISOString()}`);
      output += `Test Event ID: ${eventId}\n`;
      output += 'Test event was sent to Sentry. Check your Sentry dashboard to confirm it was received.\n\n';
      
      try {
        throw new Error('Test exception from diagnostics endpoint');
      } catch (ex) {
        const exceptionId = fastify.sentry.captureException(ex);
        output += `Test Exception ID: ${exceptionId}\n`;
      }
    } catch (ex) {
      output += `Error sending test event: ${ex.message}\n`;
      output += ex.stack || '';
    }
    
    output += '\n## Connectivity Check\n';
    output += 'If events are not appearing in Sentry, check the following:\n';
    output += '1. Verify your DSN is correct in your .env file\n';
    output += '2. Ensure your network allows outbound HTTPS connections to sentry.io\n';
    output += '3. Check Sentry server logs for any ingestion issues\n';
    output += '4. Verify your Sentry project is correctly configured to receive events\n';
    
    reply.type('text/plain').send(output);
  });

  // Test endpoint with explicit capture
  fastify.get('/test-sentry', {
    schema: {
      tags: ['Sentry'],
      description: 'Tests Sentry error reporting with a handled exception',
      response: {
        200: Type.Object({
          message: Type.String(),
          timestamp: Type.String()
        })
      }
    }
  }, async (request, reply) => {
    try {
      throw new Error(`Test exception for Sentry - ${new Date().toISOString()}`);
    } catch (ex) {
      fastify.sentry.captureException(ex);
      console.log(`Captured exception in Sentry: ${ex.message}`);
      fastify.sentry.captureMessage('This is a test message from Web3Proxy');
      return { 
        message: 'Error captured by Sentry', 
        timestamp: new Date().toISOString() 
      };
    }
  });

  // Test endpoint that throws an uncaught exception
  fastify.get('/test-sentry-uncaught', {
    schema: {
      tags: ['Sentry'],
      description: 'Tests Sentry error reporting with an unhandled exception',
      response: {
        200: Type.Object({
          message: Type.String()
        })
      }
    }
  }, async () => {
    console.log('About to throw an uncaught exception for Sentry to capture');
    throw new Error(`Uncaught exception test for Sentry - ${new Date().toISOString()}`);
  });
}

export default plugin; 