using Meezi.Core.Interfaces;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace Meezi.Infrastructure.ExternalServices;

public class SnappfoodClient : ISnappfoodClient
{
    private readonly HttpClient _httpClient;
    private readonly IConfiguration _configuration;
    private readonly ILogger<SnappfoodClient> _logger;

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

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

    public Task NotifyOrderDeliveredAsync(string snappfoodOrderId, CancellationToken cancellationToken = default) =>
        PostStatusAsync(snappfoodOrderId, "delivered", cancellationToken);

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

    private async Task PostStatusAsync(string snappfoodOrderId, string status, CancellationToken cancellationToken)
    {
        var apiKey = _configuration["Snappfood:ApiKey"];
        var baseUrl = _configuration["Snappfood:ApiBaseUrl"];
        if (string.IsNullOrWhiteSpace(apiKey) || string.IsNullOrWhiteSpace(baseUrl))
        {
            _logger.LogInformation("Snappfood API not configured — delivered notify for order {OrderId}", snappfoodOrderId);
            return;
        }

        using var request = new HttpRequestMessage(
            HttpMethod.Post,
            $"{baseUrl.TrimEnd('/')}/orders/{snappfoodOrderId}/{status}");
        request.Headers.Add("X-Api-Key", apiKey);
        var response = await _httpClient.SendAsync(request, cancellationToken);
        if (!response.IsSuccessStatusCode)
            _logger.LogWarning("Snappfood deliver notify failed {Status} for {OrderId}", response.StatusCode, snappfoodOrderId);
    }
}
