using Sentry;
using System.Text;

namespace Managing.Api.Middleware
{
    public class SentryDiagnosticsMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<SentryDiagnosticsMiddleware> _logger;

        public SentryDiagnosticsMiddleware(RequestDelegate next, ILogger<SentryDiagnosticsMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            // Only activate for the /api/sentry-diagnostics endpoint
            if (context.Request.Path.StartsWithSegments("/api/sentry-diagnostics"))
            {
                await HandleDiagnosticsRequest(context);
                return;
            }

            await _next(context);
        }

        private async Task HandleDiagnosticsRequest(HttpContext context)
        {
            var response = new StringBuilder();
            response.AppendLine("Sentry Diagnostics Report");
            response.AppendLine("========================");
            response.AppendLine($"Timestamp: {DateTime.Now}");
            response.AppendLine();

            // Check if Sentry is initialized
            response.AppendLine("## Sentry SDK Status");
            response.AppendLine($"Sentry Enabled: {SentrySdk.IsEnabled}");
            response.AppendLine($"Application Environment: {Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}");
            response.AppendLine();
            
            // Send a test event
            response.AppendLine("## Test Event");
            try
            {
                var id = SentrySdk.CaptureMessage($"Diagnostics test from {context.Request.Host} at {DateTime.Now}", SentryLevel.Info);
                response.AppendLine($"Test Event ID: {id}");
                response.AppendLine("Test event was sent to Sentry. Check your Sentry dashboard to confirm it was received.");
                
                // Try to send an exception too
                try
                {
                    throw new Exception("Test exception from diagnostics middleware");
                }
                catch (Exception ex)
                {
                    var exceptionId = SentrySdk.CaptureException(ex);
                    response.AppendLine($"Test Exception ID: {exceptionId}");
                }
            }
            catch (Exception ex)
            {
                response.AppendLine($"Error sending test event: {ex.Message}");
                response.AppendLine(ex.StackTrace);
            }

            response.AppendLine();
            response.AppendLine("## Connectivity Check");
            response.AppendLine("If events are not appearing in Sentry, check the following:");
            response.AppendLine("1. Verify your DSN is correct in appsettings.json");
            response.AppendLine("2. Ensure your network allows outbound HTTPS connections to sentry.apps.managing.live");
            response.AppendLine("3. Check Sentry server logs for any ingestion issues");
            response.AppendLine("4. Verify your Sentry project is correctly configured to receive events");
            
            // Return the diagnostic information
            context.Response.ContentType = "text/plain";
            await context.Response.WriteAsync(response.ToString());
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class SentryDiagnosticsMiddlewareExtensions
    {
        public static IApplicationBuilder UseSentryDiagnostics(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<SentryDiagnosticsMiddleware>();
        }
    }
} 