namespace MiningService.API.ExternalServices;

/// <summary>
/// EN: Client interface for Wallet Service communication.
/// VI: Interface client giao tiếp với Wallet Service.
/// </summary>
public interface IWalletServiceClient
{
    Task<bool> TransferPointsAsync(Guid userId, decimal amount, string description, CancellationToken cancellationToken = default);
    Task<WalletBalance?> GetBalanceAsync(Guid userId, CancellationToken cancellationToken = default);
}

public record WalletBalance(Guid WalletId, Guid UserId, decimal AvailableBalance, decimal PendingBalance);

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

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

    public async Task<bool> TransferPointsAsync(Guid userId, decimal amount, string description, CancellationToken cancellationToken = default)
    {
        try
        {
            var request = new { UserId = userId, Amount = amount, Description = description, Source = "Mining" };
            var response = await _httpClient.PostAsJsonAsync("/api/v1/points/add", request, cancellationToken);
            
            if (!response.IsSuccessStatusCode)
            {
                _logger.LogWarning("Failed to transfer points for {UserId}: {StatusCode}", userId, response.StatusCode);
                return false;
            }
            
            _logger.LogInformation("Transferred {Amount} points to user {UserId}", amount, userId);
            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error calling Wallet Service for user {UserId}", userId);
            return false;
        }
    }

    public async Task<WalletBalance?> GetBalanceAsync(Guid userId, CancellationToken cancellationToken = default)
    {
        try
        {
            var response = await _httpClient.GetAsync($"/api/v1/wallets/user/{userId}/balance", cancellationToken);
            if (!response.IsSuccessStatusCode) return null;
            return await response.Content.ReadFromJsonAsync<WalletBalance>(cancellationToken);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error getting wallet balance for user {UserId}", userId);
            return null;
        }
    }
}
