using System.Net.Http.Json;
using Meezi.Core.Interfaces;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace Meezi.Infrastructure.ExternalServices;

public class Tap30Client : ITap30Client
{
    private readonly HttpClient _httpClient;
    private readonly IConfiguration _configuration;
    private readonly ILogger<Tap30Client> _logger;

    public Tap30Client(HttpClient httpClient, IConfiguration configuration, ILogger<Tap30Client> logger)
    {
        _httpClient = httpClient;
        _configuration = configuration;
        _logger = logger;
    }

    public Task AcknowledgeOrderAsync(string tap30OrderId, CancellationToken cancellationToken = default) =>
        PostStatusAsync(tap30OrderId, "confirmed", cancellationToken);

    public Task NotifyOrderStatusAsync(
        string tap30OrderId,
        string status,
        CancellationToken cancellationToken = default) =>
        PostStatusAsync(tap30OrderId, status, cancellationToken);

    private async Task PostStatusAsync(string orderId, string status, CancellationToken cancellationToken)
    {
        var apiKey = _configuration["DeliveryPlatforms:Tap30:ApiKey"]
            ?? _configuration["Tap30:ApiKey"];
        var baseUrl = _configuration["DeliveryPlatforms:Tap30:ApiBaseUrl"]
            ?? _configuration["Tap30:ApiBaseUrl"];

        if (string.IsNullOrWhiteSpace(apiKey) || string.IsNullOrWhiteSpace(baseUrl))
        {
            _logger.LogInformation("Tap30 API not configured — status {Status} for {OrderId}", status, orderId);
            return;
        }

        using var request = new HttpRequestMessage(
            HttpMethod.Post,
            $"{baseUrl.TrimEnd('/')}/orders/{orderId}/status");
        request.Headers.Add("X-Api-Key", apiKey);
        request.Content = JsonContent.Create(new { status });

        var response = await _httpClient.SendAsync(request, cancellationToken);
        if (!response.IsSuccessStatusCode)
            _logger.LogWarning("Tap30 status callback failed {Status} for {OrderId}", response.StatusCode, orderId);
    }
}
