// EN: HttpClient-based implementation of IWalletServiceClient.
// VI: Implementation dựa trên HttpClient của IWalletServiceClient.

using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.Extensions.Logging;

namespace OrderService.Infrastructure.ExternalServices;

/// <summary>
/// EN: Wallet-service client — calls wallet-service REST API for payment creation.
/// VI: Wallet-service client — gọi wallet-service REST API để tạo thanh toán.
/// </summary>
public class WalletServiceClient : IWalletServiceClient
{
    private readonly HttpClient _httpClient;
    private readonly ILogger<WalletServiceClient> _logger;

    private static readonly JsonSerializerOptions _jsonOptions = new()
    {
        PropertyNameCaseInsensitive = true
    };

    public WalletServiceClient(
        HttpClient httpClient,
        ILogger<WalletServiceClient> logger)
    {
        _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    /// <inheritdoc />
    public async Task<CreatePaymentResponse?> CreatePaymentAsync(
        Guid orderId,
        decimal amount,
        string gateway,
        string returnUrl,
        string ipAddress,
        CancellationToken cancellationToken = default)
    {
        _logger.LogInformation(
            "EN: Creating payment via wallet-service: orderId={OrderId}, amount={Amount}, gateway={Gateway} / VI: Tạo thanh toán qua wallet-service: orderId={OrderId}, amount={Amount}, gateway={Gateway}",
            orderId, amount, gateway);

        var request = new
        {
            orderId,
            amount,
            gateway,
            returnUrl,
            ipAddress,
            description = $"Payment for order {orderId}"
        };

        var response = await _httpClient.PostAsJsonAsync(
            "/api/v1/payments/create",
            request,
            cancellationToken);

        if (!response.IsSuccessStatusCode)
        {
            var errorContent = await response.Content.ReadAsStringAsync(cancellationToken);
            _logger.LogError(
                "EN: Wallet-service payment creation failed: {StatusCode} - {Error} / VI: Tạo thanh toán wallet-service thất bại: {StatusCode} - {Error}",
                response.StatusCode, errorContent);
            return null;
        }

        var result = await response.Content.ReadFromJsonAsync<CreatePaymentResponse>(
            _jsonOptions, cancellationToken);

        _logger.LogInformation(
            "EN: Payment created successfully: txnId={TxnId} / VI: Tạo thanh toán thành công: txnId={TxnId}",
            result?.TransactionId);

        return result;
    }
}
