// EN: Handler for LogoutCommand - logs out the user.
// VI: Handler cho LogoutCommand - logout user.

using MediatR;
using Microsoft.AspNetCore.Identity;
using IamService.Domain.AggregatesModel.UserAggregate;

namespace IamService.API.Application.Commands.Auth;

/// <summary>
/// EN: Handler for LogoutCommand - logs out the user.
/// VI: Handler cho LogoutCommand - logout user.
/// </summary>
public class LogoutCommandHandler : IRequestHandler<LogoutCommand, LogoutCommandResult>
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly SignInManager<ApplicationUser> _signInManager;
    private readonly ILogger<LogoutCommandHandler> _logger;

    public LogoutCommandHandler(
        UserManager<ApplicationUser> userManager,
        SignInManager<ApplicationUser> signInManager,
        ILogger<LogoutCommandHandler> logger)
    {
        _userManager = userManager;
        _signInManager = signInManager;
        _logger = logger;
    }

    public async Task<LogoutCommandResult> Handle(LogoutCommand request, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Logging out user: {UserId}", request.UserId);

        var user = await _userManager.FindByIdAsync(request.UserId.ToString());

        if (user == null)
        {
            _logger.LogWarning("User not found during logout: {UserId}", request.UserId);
            // EN: Still return success - user doesn't exist, so effectively logged out
            // VI: Vẫn trả về success - user không tồn tại, nên coi như đã logout
            return new LogoutCommandResult(true, "User logged out.");
        }

        try
        {
            // EN: Sign out from Identity
            // VI: Đăng xuất khỏi Identity
            await _signInManager.SignOutAsync();

            _logger.LogInformation("User {UserId} logged out successfully", request.UserId);
            return new LogoutCommandResult(true, "User logged out successfully.");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to logout user {UserId}", request.UserId);
            return new LogoutCommandResult(true, "User logged out. Session cleanup may be pending.");
        }
    }
}
