using MediatR;
using SocialService.Domain.AggregatesModel.RelationshipAggregate;
using SocialService.Domain.AggregatesModel.UserProfileAggregate;

namespace SocialService.API.Application.Queries;

/// <summary>
/// EN: Handler for GetFriendsQuery.
/// VI: Handler cho GetFriendsQuery.
/// </summary>
public class GetFriendsQueryHandler : IRequestHandler<GetFriendsQuery, GetFriendsResult>
{
    private readonly IRelationshipRepository _relationshipRepository;
    private readonly IUserProfileRepository _userProfileRepository;

    public GetFriendsQueryHandler(
        IRelationshipRepository relationshipRepository,
        IUserProfileRepository userProfileRepository)
    {
        _relationshipRepository = relationshipRepository;
        _userProfileRepository = userProfileRepository;
    }

    public async Task<GetFriendsResult> Handle(GetFriendsQuery request, CancellationToken cancellationToken)
    {
        var friendships = await _relationshipRepository.GetFriendsAsync(request.UserId, request.Skip, request.Take);
        var totalCount = await _relationshipRepository.GetFriendsCountAsync(request.UserId);

        // EN: Extract friend user IDs
        // VI: Trích xuất ID của bạn bè
        var friendUserIds = friendships.Select(f => 
            f.RequesterId == request.UserId ? f.AddresseeId : f.RequesterId
        ).ToList();

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

        var friends = friendships.Select(f =>
        {
            var friendId = f.RequesterId == request.UserId ? f.AddresseeId : f.RequesterId;
            var profile = profileDict.GetValueOrDefault(friendId);
            
            return new FriendDto(
                friendId,
                profile?.DisplayName ?? "Unknown",
                profile?.AvatarUrl,
                f.CreatedAt
            );
        });

        return new GetFriendsResult(friends, totalCount);
    }
}
