namespace MiningService.API.ExternalServices;

/// <summary>
/// EN: Client interface for Social Service communication.
/// VI: Interface client giao tiếp với Social Service.
/// </summary>
public interface ISocialServiceClient
{
    Task<List<FriendSuggestion>> GetFriendSuggestionsAsync(Guid userId, int limit = 10, CancellationToken cancellationToken = default);
    Task<bool> AreFriendsAsync(Guid userId1, Guid userId2, CancellationToken cancellationToken = default);
}

public record FriendSuggestion(Guid UserId, string DisplayName, int MutualFriends, decimal TrustScore);

/// <summary>
/// EN: HTTP client implementation for Social Service.
/// VI: Triển khai HTTP client cho Social Service.
/// </summary>
public class SocialServiceClient : ISocialServiceClient
{
    private readonly HttpClient _httpClient;
    private readonly ILogger<SocialServiceClient> _logger;

    public SocialServiceClient(HttpClient httpClient, ILogger<SocialServiceClient> logger)
    {
        _httpClient = httpClient;
        _logger = logger;
    }

    public async Task<List<FriendSuggestion>> GetFriendSuggestionsAsync(Guid userId, int limit = 10, CancellationToken cancellationToken = default)
    {
        try
        {
            var response = await _httpClient.GetAsync($"/api/v1/social/friends/{userId}/suggestions?limit={limit}", cancellationToken);
            if (!response.IsSuccessStatusCode)
            {
                _logger.LogWarning("Failed to get friend suggestions for {UserId}: {StatusCode}", userId, response.StatusCode);
                return new List<FriendSuggestion>();
            }
            return await response.Content.ReadFromJsonAsync<List<FriendSuggestion>>(cancellationToken) ?? new();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error calling Social Service for user {UserId}", userId);
            return new List<FriendSuggestion>();
        }
    }

    public async Task<bool> AreFriendsAsync(Guid userId1, Guid userId2, CancellationToken cancellationToken = default)
    {
        try
        {
            var response = await _httpClient.GetAsync($"/api/v1/social/friends/{userId1}/check/{userId2}", cancellationToken);
            if (!response.IsSuccessStatusCode) return false;
            var result = await response.Content.ReadFromJsonAsync<FriendCheckResult>(cancellationToken);
            return result?.AreFriends ?? false;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error checking friendship between {UserId1} and {UserId2}", userId1, userId2);
            return false;
        }
    }

    private record FriendCheckResult(bool AreFriends);
}
