using System.Text;
using ms_namingservice.Objects;
using Newtonsoft.Json;
using webApiGateway.Objects;

namespace webApiGateway.HttpRequests;

/// <summary>
/// Class for communication with ms-namingService.
/// </summary>
public class NamingService
{
    /// <summary>
    /// Represents the logger instance for this class.
    /// </summary>
    private static ILogger Logger = Logging.LoggerFactory.CreateLogger<NamingService>();

    /// <summary>
    /// Asynchronously sends a POST request to the naming service API with the provided input object,
    /// and returns the generated name for the framework specified in the input object.
    /// </summary>
    /// <param name="input">The input object containing the framework name.</param>
    /// <returns>The generated name for the specified framework, or a default value if the API response is invalid.</returns>
    public static async Task<string> GetGeneratedName(Input input)
    {
        //Log input to the service
        Logger.LogInformation("Input object into ms-namingservice: " + JsonConvert.SerializeObject(input));

        //Getting URL
        var configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build();

        var URL = configuration.GetValue<string>("EndpointUrls:NamingService");

        //Sending HTTP request
        using var httpClient = new HttpClient();
        var jsonString = JsonConvert.SerializeObject(input);
        var content = new StringContent(jsonString, Encoding.UTF8, "application/json");

        //Getting response and parsing it into object
        var response = await httpClient.PostAsync(URL, content);

        if (!response.IsSuccessStatusCode) Logger.LogError("Bad response from ms-namingService: " + response);

        var responseContent = await response.Content.ReadAsStringAsync();

        //Getting final object "Output" from ms-namingService
        var output = JsonConvert.DeserializeObject<Output>(responseContent);

        //Retrieving the generated name for the framework input for GUI for the specified use case
        foreach (var framework in output.Frameworks)
            if (framework.Name.Equals(GuiInput.Input.Framework)) //Condition in order to match the user`s input framework in GUI
            {
                Logger.LogInformation("Generated name returned: " + framework.GeneratedName); //Log the generated name
                return framework.GeneratedName;
            }

        return "null-null_null-null_null:null"; //Default value for generated name, if nothing is matched 
    }
}