using MediatR;
using SocialService.API.Controllers;
using SocialService.Domain.AggregatesModel.UserBlockAggregate;
using SocialService.Domain.AggregatesModel.UserProfileAggregate;

namespace SocialService.API.Application.Queries;

/// <summary>
/// EN: Handler for GetBlockedUsersQuery.
/// VI: Handler cho GetBlockedUsersQuery.
/// </summary>
public class GetBlockedUsersQueryHandler : IRequestHandler<GetBlockedUsersQuery, GetBlockedUsersResult>
{
    private readonly IUserBlockRepository _userBlockRepository;
    private readonly IUserProfileRepository _userProfileRepository;

    public GetBlockedUsersQueryHandler(
        IUserBlockRepository userBlockRepository,
        IUserProfileRepository userProfileRepository)
    {
        _userBlockRepository = userBlockRepository;
        _userProfileRepository = userProfileRepository;
    }

    public async Task<GetBlockedUsersResult> Handle(GetBlockedUsersQuery request, CancellationToken cancellationToken)
    {
        var blocks = await _userBlockRepository.GetBlockedByUserAsync(request.UserId, request.Skip, request.Take);
        var totalCount = await _userBlockRepository.GetBlockedCountAsync(request.UserId);

        var blockList = blocks.ToList();
        var blockedUserIds = blockList.Select(b => b.BlockedId).ToList();

        // EN: Get user profiles for display
        // VI: Lấy hồ sơ user để hiển thị
        var profiles = await _userProfileRepository.GetByUserIdsAsync(blockedUserIds);
        var profileDict = profiles.ToDictionary(p => p.UserId, p => p);

        var blockedUsers = blockList.Select(b =>
        {
            var profile = profileDict.GetValueOrDefault(b.BlockedId);
            return new BlockedUserDto(
                b.BlockedId,
                profile?.DisplayName ?? "Unknown",
                profile?.AvatarUrl,
                b.CreatedAt,
                b.Reason
            );
        });

        return new GetBlockedUsersResult(blockedUsers, totalCount);
    }
}
