using Newtonsoft.Json;
using webApiGateway.Objects;
using webApiGateway.Objects.Objects;

namespace webApiGateway.HttpRequests;

/// <summary>
/// Class for communication with ms-useCaseService.
/// </summary>
public class UseCaseService
{
    /// <summary>
    /// Represents the logger instance for this class.
    /// </summary>
    private static ILogger Logger = Logging.LoggerFactory.CreateLogger<UseCaseService>();
    
    /// <summary>
    /// Gets a list of use cases that match the specified query, which maps the final use cases to the log source.
    /// </summary>
    /// <param name="query">The query to match use cases against.</param>
    /// <returns>A list of use cases that match the specified query.</returns>
    public static async Task<List<UseCase>> GetUseCases(string query)
    {
        //Logging the input to the service
        Logger.LogInformation("Query input into ms-useCaseService: " + query); 
        
        List<UseCase> useCases = new List<UseCase>();

        //Getting the URL of the endpoint and constructing a HTTP GET URL
        var configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build();
        string URL = configuration.GetValue<string>("EndpointUrls:UseCaseService");
        var getURL = URL + $"?query={query}";
        
        //Sending the HTTP request
        using HttpClient httpClient = new HttpClient();
        HttpResponseMessage response = await httpClient.GetAsync(getURL);
        
        if (!response.IsSuccessStatusCode) Logger.LogError("Bad response from ms-useCaseService: " + response);

        //Parsing the response JSON to the List<UseCase> object
        string responseBody = await response.Content.ReadAsStringAsync();
        useCases = JsonConvert.DeserializeObject<List<UseCase>>(responseBody);
        
        //Logging and returning the list of use cases for the specified log source, which is represented by the query
        Logger.LogInformation("Use cases output from ms-useCaseService: " + JsonConvert.SerializeObject(useCases)); 
        return useCases;
    }
}