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

namespace webApiGateway.HttpRequests;

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

    /// <summary>
    /// Sends the specified log source to the endpoint URL and returns the query result. This query is used to retrieve use cases from another service.
    /// </summary>
    /// <param name="LogSource">The log source to map the use cases.</param>
    /// <returns>A task representing the asynchronous operation, which returns the query for use cases as a string.</returns>
    public static async Task<string> SendLogSource(LogSource logSource) 
    {
        // Serialize the log source to JSON and log it.
        Logger.LogInformation("LogSource input to ms-mappingService: " + JsonConvert.SerializeObject(logSource)); 

        var settings = new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver()
        };
        string json = JsonConvert.SerializeObject(logSource, Formatting.Indented, settings);

        // Get the endpoint URL from the appsettings.json file.
        var configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build();

        string URL = configuration.GetValue<string>("EndpointUrls:MappingService");
    
        // Send an HTTP POST request to the endpoint URL with the serialized JSON data.
        using var httpClient = new HttpClient();
        using var request = new HttpRequestMessage(new HttpMethod("POST"), URL)
        {
            Content = new StringContent(json, Encoding.UTF8, "application/json")
        };
        var response = await httpClient.SendAsync(request);
        
        if (!response.IsSuccessStatusCode) Logger.LogError("Bad response from ms-mappingService: " + response);

        string query = await response.Content.ReadAsStringAsync(); //Query to ms-UseCaseService

        // Log the returned query and return it.
        Logger.LogInformation("Query returned: " + query);  
        return query;
    }
}