using System.Data.OleDb; using System.Text.Json; using System.Text.Json.Nodes; namespace TarifasANEEL.Services { public class ApiException : Exception { public ApiException(string message, Exception? innerException = null) : base(message, innerException) { } } public static class ApiService { private static readonly HttpClient HttpClient = new(); public static string BuildUrl(string baseUrl, Dictionary reader, string yearColumn) { string sWebString = $@"{baseUrl}?"; foreach (var kvp in reader) { if (kvp.Key != yearColumn && kvp.Value.ToString() != "") { sWebString = $@"{sWebString}{kvp.Key}={kvp.Value}&"; } } return sWebString; } public static async Task PullDataAsync(string url) { try { using var response = await HttpClient.GetAsync(url); response.EnsureSuccessStatusCode(); var responseContent = await response.Content.ReadAsStringAsync(); return JsonNode.Parse(CleanJson(responseContent)) ?? throw new JsonException("Failed to parse API response"); } catch (HttpRequestException ex) { throw new ApiException($"API request failed: {url}", ex); } catch (JsonException ex) { throw new ApiException("Invalid JSON response", ex); } } private static string CleanJson(string responseContent) { return responseContent.ToString() .Replace(@"""NomPostoTarifario"":""Não se aplica""", @"""NomPostoTarifario"":""N""") .Replace(@"""DscPostoTarifario"":""Não se aplica""", @"""DscPostoTarifario"":""N""") .Replace(@"""DscSubClasseConsumidor"":""Residencial""", @"""DscSubClasseConsumidor"":""""") .Replace(@"""DscClasseConsumidor"":""Iluminação pública""", @"""DscClasseConsumidor"":""""") .Replace(@"""DscModalidadeTarifaria"":""Convencional pré-pagamento""", @"""DscModalidadeTarifaria"":""pré-pagamento""") .Replace(@"""Não se aplica""", @""""""); } } }