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

namespace SocialService.API.Application.Queries;

/// <summary>
/// EN: Handler for GetFriendSuggestionsQuery.
/// VI: Handler cho GetFriendSuggestionsQuery.
/// </summary>
public class GetFriendSuggestionsQueryHandler : IRequestHandler<GetFriendSuggestionsQuery, GetFriendSuggestionsResult>
{
    private readonly IGraphQueryService _graphQueryService;
    private readonly IUserProfileRepository _userProfileRepository;

    public GetFriendSuggestionsQueryHandler(
        IGraphQueryService graphQueryService,
        IUserProfileRepository userProfileRepository)
    {
        _graphQueryService = graphQueryService;
        _userProfileRepository = userProfileRepository;
    }

    public async Task<GetFriendSuggestionsResult> Handle(GetFriendSuggestionsQuery request, CancellationToken cancellationToken)
    {
        var suggestions = await _graphQueryService.GetFriendSuggestionsAsync(request.UserId, request.Limit);
        var suggestionList = suggestions.ToList();

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

        var result = suggestionList.Select(s =>
        {
            var profile = profileDict.GetValueOrDefault(s.UserId);
            return new FriendSuggestionDto(
                s.UserId,
                profile?.DisplayName ?? "Unknown",
                profile?.AvatarUrl,
                s.MutualFriendsCount
            );
        });

        return new GetFriendSuggestionsResult(result);
    }
}
