using System.Text.Json;
using System.Globalization;

namespace StockFin
{
    public class AlphaVantageService
    {
        private readonly HttpClient _httpClient;
        private readonly IConfiguration _configuration;

        public AlphaVantageService(
            HttpClient httpClient,
            IConfiguration configuration)
        {
            _httpClient = httpClient;
            _configuration = configuration;
        }

        private string ApiKey =>
            _configuration["AlphaVantage:ApiKey"]!;

        public async Task<StockQuote?> GetQuoteAsync(
            string isin,
            string ticker)
        {
            var url =
                $"https://www.alphavantage.co/query" +
                $"?function=GLOBAL_QUOTE" +
                $"&symbol={ticker}" +
                $"&apikey={ApiKey}";

            var json = await _httpClient.GetStringAsync(url);

            using var doc = JsonDocument.Parse(json);

            if (!doc.RootElement.TryGetProperty("Global Quote", out var quote))
                return null;

            return new StockQuote
            {
                Isin = isin,
                Symbol = ticker,
                CurrentPrice =
                    double.Parse(
                        quote.GetProperty("05. price").GetString()!,CultureInfo.InvariantCulture),

                PreviousClose =
                    double.Parse(
                        quote.GetProperty("08. previous close").GetString()!, CultureInfo.InvariantCulture),

                QuoteTime = DateTime.Now
            };
        }

        public async Task<HistoricalPrice?> GetPriceAtDateAsync(
            string ticker,
            DateTime date)
        {
            var url =
                $"https://www.alphavantage.co/query" +
                $"?function=TIME_SERIES_DAILY" +
                $"&symbol={ticker}" +
                $"&outputsize=full" +
                $"&apikey={ApiKey}";

            var json = await _httpClient.GetStringAsync(url);

            using var doc = JsonDocument.Parse(json);

            var series =
                doc.RootElement.GetProperty("Time Series (Daily)");

            var key = date.ToString("yyyy-MM-dd");

            if (!series.TryGetProperty(key, out var day))
                return null;

            return new HistoricalPrice
            {
                Date = date.Date,
                Close = double.Parse(
                    day.GetProperty("4. close").GetString()!, CultureInfo.InvariantCulture)
            };
        }
    }
    public class StockQuote
    {
        public string Isin { get; set; } = "";
        public string Symbol { get; set; } = "";

        public double CurrentPrice { get; set; }
        public double PreviousClose { get; set; }

        public DateTime QuoteTime { get; set; }
    }
    public class HistoricalPrice
    {
        public DateTime Date { get; set; }
        public double Close { get; set; }
    }
}
