using Brizco.Domain.Entities.Complex;
using Brizco.Domain.Entities.User;
using Microsoft.IdentityModel.Tokens;

namespace Brizco.Repository.Handlers.Complex;

public class GetComplexUsersQueryHandler : IRequestHandler<GetComplexUsersQuery, List<ComplexUserSDto>>
{
    private readonly IRepositoryWrapper _repositoryWrapper;
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly RoleManager<ApplicationRole> _roleManager;

    public GetComplexUsersQueryHandler(IRepositoryWrapper repositoryWrapper, UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager)
    {
        _repositoryWrapper = repositoryWrapper;
        _userManager = userManager;
        _roleManager = roleManager;
    }
    public async Task<List<ComplexUserSDto>> Handle(GetComplexUsersQuery request, CancellationToken cancellationToken)
    {
        List<ComplexUserSDto> list = new List<ComplexUserSDto>();
        if (!request.ComplexId.IsNullOrEmpty() && Guid.TryParse(request.ComplexId, out Guid complexId))
        {
            list = await _repositoryWrapper.SetRepository<ComplexUser>().TableNoTracking
                .Where(c => c.ComplexId == complexId)
                .OrderByDescending(s => s.CreatedAt)
                .Skip(request.Page * 15).Take(15)
                .Select(ComplexUserMapper.ProjectToSDto)
                .ToListAsync(cancellationToken);
        }
        else
        {
            list = await _repositoryWrapper.SetRepository<ComplexUser>().TableNoTracking
                .OrderByDescending(s => s.CreatedAt)
                .Skip(request.Page * 15).Take(15)
                .Select(ComplexUserMapper.ProjectToSDto)
                .ToListAsync(cancellationToken);
        }



        foreach (var complexUser in list)
        {
            var user = await _userManager.FindByIdAsync(complexUser.UserId.ToString());
            if (user != null)
            {
                var roleIds = await _userManager.GetRolesAsync(user);
                foreach (var roleId in roleIds)
                {
                    var role = await _roleManager.FindByNameAsync(roleId);
                    if(role!= null)
                        complexUser.RoleNames.Add(role.PersianName);
                }
            }
        }

        return list;

    }
}