using System.Text.Json;

namespace economy.Models.FIFA
{
    public class FIFAModel
    {
        private readonly FIFA_API _fifaAPI;

        public FIFAModel(FIFA_API fifaAPI)
        {
            _fifaAPI = fifaAPI;
        }

        // FIFA 순위
        public async Task<Response> GetRanking(Request request)
        {
            Response parseData = new();

            try
            {
                var uriBuilder = new UriBuilder(_fifaAPI.APIUrl)
                {
                    Path = "/api/v3/rankings",
                    Query = $"gender={request.Gender}&count={request.NumOfRows}&language=ko"
                };

                var response = await _fifaAPI.httpClient.GetAsync(uriBuilder.Uri);

                if (response.IsSuccessStatusCode)
                {
                    var jsonString = await response.Content.ReadAsStringAsync();
                    parseData = JsonSerializer.Deserialize<Response>(jsonString);

                    if (parseData is null)
                    {
                        return new Response();
                    }
                }

                response.EnsureSuccessStatusCode();
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"Request error: {e.Message}");
            }

            return parseData;
        }
    }
}
