using Indotalent.Data.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;

namespace Indotalent.Features.Setting.SystemUser.Cqrs;

public class ChangeRoleResponse
{
    public bool IsSuccess { get; set; }
    public string Message { get; set; } = string.Empty;
}

public class ChangeRoleRequest
{
    public string UserId { get; set; } = string.Empty;
    public List<string> Roles { get; set; } = new();
}

public record ChangeRoleCommand(ChangeRoleRequest Data) : IRequest<ChangeRoleResponse>;

public class ChangeRoleHandler : IRequestHandler<ChangeRoleCommand, ChangeRoleResponse>
{
    private readonly UserManager<ApplicationUser> _userManager;

    public ChangeRoleHandler(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    public async Task<ChangeRoleResponse> Handle(ChangeRoleCommand request, CancellationToken cancellationToken)
    {
        var user = await _userManager.FindByIdAsync(request.Data.UserId);
        if (user == null) return new ChangeRoleResponse { IsSuccess = false, Message = "User not found" };

        var currentRoles = await _userManager.GetRolesAsync(user);

        var removeResult = await _userManager.RemoveFromRolesAsync(user, currentRoles);
        if (!removeResult.Succeeded) return new ChangeRoleResponse { IsSuccess = false, Message = "Remove role fail" };

        var addResult = await _userManager.AddToRolesAsync(user, request.Data.Roles);
        return new ChangeRoleResponse
        {
            IsSuccess = true,
            Message = "Roles updated successfully"
        };
    }
}