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

namespace Predictalytics.Infrastructure.Providers.Limitless;

/// <summary>
/// HTTP client for Limitless API.
/// Base URL: https://api.limitless.exchange
/// </summary>
public class LimitlessApiClient
{
    private readonly HttpClient _client;
    private readonly ILogger<LimitlessApiClient> _logger;

    public LimitlessApiClient(IHttpClientFactory httpFactory, ILogger<LimitlessApiClient> logger)
    {
        _client = httpFactory.CreateClient("LimitlessApi");
        _logger = logger;
    }

    public async Task<List<LimitlessMarketResponse>> GetActiveMarketsAsync(int limit = 100, int offset = 0, CancellationToken ct = default)
    {
        var url = $"markets/active?limit={Math.Min(limit, 25)}"; // Offset is not supported by this endpoint, limit max 25
        try
        {

            var response = await _client.GetAsync(url, ct);
            if (!response.IsSuccessStatusCode)
            {
                var error = await response.Content.ReadAsStringAsync(ct);
                _logger.LogError("Limitless API 400/Error for {Url}: {Error}", url, error);
                return [];
            }
            var result = await response.Content.ReadFromJsonAsync<LimitlessActiveMarketsResponse>(cancellationToken: ct);
            return result?.Data ?? [];
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to fetch active markets from Limitless via {Url}", url);
            return [];
        }
    }

    public async Task<LimitlessMarketResponse?> GetMarketAsync(string addressOrSlug, CancellationToken ct = default)
    {
        var url = $"markets/{addressOrSlug}";
        try
        {

            var response = await _client.GetAsync(url, ct);
            if (!response.IsSuccessStatusCode) return null;
            return await response.Content.ReadFromJsonAsync<LimitlessMarketResponse>(cancellationToken: ct);
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "Failed to fetch Limitless market: {Url}", url);
            return null;
        }
    }

    public async Task<LimitlessPortfolioResponse?> GetPositionsAsync(string walletAddress, CancellationToken ct = default)
    {
        var url = $"portfolio/{walletAddress}/positions";
        try
        {

            var response = await _client.GetAsync(url, ct);
            if (!response.IsSuccessStatusCode)
            {
                var error = await response.Content.ReadAsStringAsync(ct);
                _logger.LogError("Limitless API Error for {Url}: {Error}", url, error);
                return null;
            }
            return await response.Content.ReadFromJsonAsync<LimitlessPortfolioResponse>(cancellationToken: ct);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to fetch Limitless positions for {Url}", url);
            return null;
        }
    }

    public async Task<List<LimitlessEventResponse>> GetMarketEventsAsync(string slug, int limit = 50, CancellationToken ct = default)
    {
        var url = $"markets/{slug}/events?limit={limit}";
        try
        {

            var response = await _client.GetAsync(url, ct);
            if (!response.IsSuccessStatusCode) return [];
            var result = await response.Content.ReadFromJsonAsync<LimitlessEventsResponse>(cancellationToken: ct);
            return result?.Events ?? [];
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to fetch events for Limitless market {Url}", url);
            return [];
        }
    }
}
