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

namespace SocialService.API.Application.Queries;

/// <summary>
/// EN: Handler for GetMutualFriendsQuery.
/// VI: Handler cho GetMutualFriendsQuery.
/// </summary>
public class GetMutualFriendsQueryHandler : IRequestHandler<GetMutualFriendsQuery, GetMutualFriendsResult>
{
    private readonly IGraphQueryService _graphQueryService;
    private readonly IUserProfileRepository _userProfileRepository;

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

    public async Task<GetMutualFriendsResult> Handle(GetMutualFriendsQuery request, CancellationToken cancellationToken)
    {
        var mutualFriendIds = await _graphQueryService.GetMutualFriendsAsync(request.UserId1, request.UserId2);
        var mutualFriendIdList = mutualFriendIds.ToList();

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

        var mutualFriends = mutualFriendIdList.Select(id =>
        {
            var profile = profileDict.GetValueOrDefault(id);
            return new FriendDto(
                id,
                profile?.DisplayName ?? "Unknown",
                profile?.AvatarUrl,
                profile?.CreatedAt ?? DateTime.UtcNow
            );
        });

        return new GetMutualFriendsResult(mutualFriends, mutualFriendIdList.Count);
    }
}
