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.");

static Dictionary<string, double> Values(double fit, double demand, double margin, double cost, double risk, double customer) => new()
{
    ["determine_trade_in_value_vehicle_fit_score"] = fit,
    ["determine_trade_in_value_market_demand_score"] = demand,
    ["determine_trade_in_value_gross_margin_potential"] = margin,
    ["determine_trade_in_value_reconditioning_or_process_cost"] = cost,
    ["determine_trade_in_value_compliance_risk_score"] = risk,
    ["determine_trade_in_value_customer_value_score"] = customer
};

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-ucd-008-csharp-{DateTimeOffset.UtcNow:yyyyMMddHHmmss}";
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(45) };

var tokenResponse = await http.PostAsJsonAsync(identityUrl, new
{
    clientId = Required("DECISIOQ_CLIENT_ID"),
    clientSecret = Required("DECISIOQ_CLIENT_SECRET"),
    audience
});
tokenResponse.EnsureSuccessStatusCode();
var jwtToken = JsonDocument.Parse(await tokenResponse.Content.ReadAsStringAsync()).RootElement.GetProperty("jwtToken").GetString();

using var metadataRequest = new HttpRequestMessage(HttpMethod.Get, $"{catalogUrl}/decisioncatalog/decisions/AUTO-UCD-008");
metadataRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken);
metadataRequest.Headers.TryAddWithoutValidation("X-Correlation-Id", correlationId);
using var metadataResponse = await http.SendAsync(metadataRequest);
metadataResponse.EnsureSuccessStatusCode();

var executionRequest = new
{
    decisionId = "AUTO-UCD-008",
    profileId = "balanced",
    scenarioId = "standard_retail",
    algorithm = "TOPSIS",
    weightStrategy = "Expert",
    runSensitivity = false,
    requestContext = new { correlationId },
    options = new object[]
    {
        new { optionId = "OPTION-001", name = "Retail Trade Option", values = Values(86, 92, 3200, 900, 22, 84) },
        new { optionId = "OPTION-002", name = "Wholesale Backup Option", values = Values(78, 73, 4100, 1600, 35, 76) },
        new { optionId = "OPTION-003", name = "Certified Retail Option", values = Values(91, 85, 2300, 650, 18, 88) }
    }
};

using var execution = new HttpRequestMessage(HttpMethod.Post, $"{decisionServiceUrl}/api/v1/decide")
{
    Content = JsonContent.Create(executionRequest)
};
execution.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken);
execution.Headers.TryAddWithoutValidation("X-Correlation-Id", correlationId);
using var executionResponse = await http.SendAsync(execution);
Console.WriteLine(await executionResponse.Content.ReadAsStringAsync());
executionResponse.EnsureSuccessStatusCode();