using Newtonsoft.Json;

namespace WeatherDashboard.Web.Services
{
    public class WeatherApiForecastService : IForecastService
    {
        private readonly IConfiguration configuration;
        private readonly string? apiBaseUrl;
        private readonly string? apiKey;
        private readonly HttpClient httpClient;

        public WeatherApiForecastService(IConfiguration configuration, IHttpClientFactory httpClientFactory)
        {
            this.configuration = configuration;

            apiBaseUrl = configuration["ApiBaseUrl"];
            apiKey = configuration["ApiKey"];

            httpClient = httpClientFactory.CreateClient();
        }

        public Task<WeatherSet> GetWeatherAsync() => InvokeRequestAsync<WeatherSet>("v1/forecast.json");

        private async Task<T> InvokeRequestAsync<T>(string method)
        {
            // sample URL
            // https://api.weatherapi.com/v1/forecast.json?key=829fbbe5beb2424aa1021928230702&q=21144&days=2&aqi=no&alerts=yes
            var url = new UriBuilder(apiBaseUrl);

            url.Path = method;
            url.Query = $"key={apiKey}&days=10&q=21144";

            var response = await httpClient.GetStringAsync(url.ToString());

            return JsonConvert.DeserializeObject<T>(response);
        }
    }
}
