using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;

static string Required(string name) =>
    Environment.GetEnvironmentVariable(name) ??
    throw new InvalidOperationException($"Set {name} before running this example.");

var identityUrl = Environment.GetEnvironmentVariable("DECISIOQ_IDENTITY_URL") ?? "https://identity.vinquery.com/connect/token";
var catalogUrl = (Environment.GetEnvironmentVariable("DECISIOQ_DKS_URL") ?? "https://dks.vinquery.com").TrimEnd('/');
var decisionServiceUrl = (Environment.GetEnvironmentVariable("DECISIOQ_DDE_URL") ?? "https://dde.vinquery.com").TrimEnd('/');
var audience = Environment.GetEnvironmentVariable("DECISIOQ_AUDIENCE") ?? "vinquery:api:decisioq";
var correlationId = $"auto-auct-006-csharp-{Guid.NewGuid():N}";

using var http = new HttpClient();

var tokenResponse = await http.PostAsJsonAsync(identityUrl, new
{
    clientId = Required("DECISIOQ_CLIENT_ID"),
    clientSecret = Required("DECISIOQ_CLIENT_SECRET"),
    audience
});
tokenResponse.EnsureSuccessStatusCode();

var tokenJson = await tokenResponse.Content.ReadFromJsonAsync<JsonElement>();
var jwtToken = tokenJson.GetProperty("jwtToken").GetString();
if (string.IsNullOrWhiteSpace(jwtToken))
{
    throw new InvalidOperationException("Token response did not contain jwtToken.");
}

http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken);
http.DefaultRequestHeaders.Add("X-Correlation-Id", correlationId);

var decisionDefinition = await http.GetAsync($"{catalogUrl}/decisioncatalog/decisions/AUTO-AUCT-006");
decisionDefinition.EnsureSuccessStatusCode();

var request = new
{
    decisionId = "AUTO-AUCT-006",
    profileId = "balanced",
    scenarioId = "standard",
    algorithm = "TOPSIS",
    weightStrategy = "Expert",
    runSensitivity = false,
    requestContext = new { correlationId },
    options = new[]
    {
        new
        {
            optionId = "MANHEIM-TORONTO",
            name = "Manheim Toronto",
            values = new Dictionary<string, double>
            {
                ["vehicle_availability_score"] = 88,
                ["buyer_fee_level"] = 1250,
                ["average_vehicle_quality"] = 88,
                ["distance_to_facility"] = 54,
                ["auction_reputation_score"] = 88,
                ["title_processing_speed"] = 88
            }
        },
        new
        {
            optionId = "ADESA-TORONTO",
            name = "ADESA Toronto",
            values = new Dictionary<string, double>
            {
                ["vehicle_availability_score"] = 81,
                ["buyer_fee_level"] = 1750,
                ["average_vehicle_quality"] = 81,
                ["distance_to_facility"] = 71,
                ["auction_reputation_score"] = 81,
                ["title_processing_speed"] = 81
            }
        }
    }
};

var executionResponse = await http.PostAsJsonAsync($"{decisionServiceUrl}/api/v1/decide", request);
var responseText = await executionResponse.Content.ReadAsStringAsync();

Console.WriteLine(responseText);
executionResponse.EnsureSuccessStatusCode();
