using DbController.SqlServer;
using DbController;
using Microsoft.AspNetCore.Http;
using Tabletop.Core.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace Tabletop.Core.Middlewares
{
    public class ConnectionLogMiddleware(RequestDelegate next, IServiceProvider serviceProvider, ILogger<ConnectionLogMiddleware> logger)
    {
        private readonly RequestDelegate _next = next;
        private readonly IServiceProvider _serviceProvider = serviceProvider;
        private readonly ILogger<ConnectionLogMiddleware> _logger = logger;

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                
                // Erstelle ein ServiceScope, um Scoped Services zu verwenden
                using var scope = _serviceProvider.CreateScope();
                var connectionLogService = scope.ServiceProvider.GetRequiredService<ConnectionLogService>();

                // Erstelle das ConnectionLog
                var connectionLog = await connectionLogService.GetConnectionLogAsync(context);

                if (connectionLog.IpAddress is not ("84.119.112.185" or "127.0.0.1" or "::1"))
                {
                    // Verwende den dbController zur Speicherung des Logs in der DB
                    using IDbController dbController = new SqlController(AppdataService.ConnectionString);
                    await ConnectionLogService.CreateAsync(connectionLog, dbController);
                }
            }
            catch (Exception ex)
            {
                // Fehlerbehandlung und Logging
                _logger.LogError($"Fehler beim Erstellen des ConnectionLogs: {ex.Message}", ex);
            }

            // Weiter zum nächsten Middleware in der Pipeline
            await _next(context);
        }
    }
}