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

namespace IamService.API.Application.Commands.Roles;

/// <summary>
/// EN: Handler for RemoveRoleFromUserCommand.
/// VI: Handler cho RemoveRoleFromUserCommand.
/// </summary>
public class RemoveRoleFromUserCommandHandler : IRequestHandler<RemoveRoleFromUserCommand, bool>
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly ILogger<RemoveRoleFromUserCommandHandler> _logger;

    public RemoveRoleFromUserCommandHandler(
        UserManager<ApplicationUser> userManager,
        ILogger<RemoveRoleFromUserCommandHandler> logger)
    {
        _userManager = userManager;
        _logger = logger;
    }

    public async Task<bool> Handle(RemoveRoleFromUserCommand request, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Removing role {RoleName} from user {UserId}", request.RoleName, request.UserId);

        // EN: Find user
        // VI: Tìm user
        var user = await _userManager.FindByIdAsync(request.UserId.ToString());
        if (user == null)
        {
            _logger.LogWarning("User not found: {UserId}", request.UserId);
            throw new DomainException($"User with ID {request.UserId} not found.");
        }

        // EN: Check if user has this role
        // VI: Kiểm tra user có role này không
        var isInRole = await _userManager.IsInRoleAsync(user, request.RoleName);
        if (!isInRole)
        {
            _logger.LogWarning("User {UserId} does not have role {RoleName}", request.UserId, request.RoleName);
            throw new DomainException($"User does not have role '{request.RoleName}'.");
        }

        // EN: Remove role from user
        // VI: Xóa role khỏi user
        var result = await _userManager.RemoveFromRoleAsync(user, request.RoleName);

        if (!result.Succeeded)
        {
            var errors = string.Join(", ", result.Errors.Select(e => e.Description));
            _logger.LogError("Failed to remove role {RoleName} from user {UserId}: {Errors}", 
                request.RoleName, request.UserId, errors);
            throw new DomainException($"Failed to remove role: {errors}");
        }

        _logger.LogInformation("Role {RoleName} removed from user {UserId} successfully", 
            request.RoleName, request.UserId);

        return true;
    }
}
