using QRRapidoApp.Services;
using System.Security.Claims;

namespace QRRapidoApp.Middleware
{
    public class LastLoginUpdateMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly IServiceScopeFactory _scopeFactory;
        private readonly ILogger<LastLoginUpdateMiddleware> _logger;

        public LastLoginUpdateMiddleware(RequestDelegate next, IServiceScopeFactory scopeFactory, ILogger<LastLoginUpdateMiddleware> logger)
        {
            _next = next;
            _scopeFactory = scopeFactory;
            _logger = logger;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            // Only update login for authenticated users on first request of session
            if (context.User.Identity?.IsAuthenticated == true)
            {
                var userId = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
                
                if (!string.IsNullOrEmpty(userId) && !context.Session.GetString("LoginUpdated")?.Equals("true") == true)
                {
                    try
                    {
                        using var scope = _scopeFactory.CreateScope();
                        var userService = scope.ServiceProvider.GetRequiredService<IUserService>();
                        
                        await userService.UpdateLastLoginAsync(userId);
                        context.Session.SetString("LoginUpdated", "true");
                        
                        _logger.LogInformation($"Updated last login for user {userId}");
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, $"Error updating last login for user {userId}: {ex.Message}");
                    }
                }
            }

            await _next(context);
        }
    }
}