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()
{
    ["assign_rental_vehicle_customer_fit_score"] = fit,
    ["assign_rental_vehicle_vehicle_or_resource_fit"] = demand,
    ["assign_rental_vehicle_operational_readiness"] = margin,
    ["assign_rental_vehicle_financial_impact"] = cost,
    ["assign_rental_vehicle_risk_exposure"] = risk,
    ["assign_rental_vehicle_time_sensitivity"] = 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-rent-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-RENT-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-RENT-008",
    profileId = "balanced",
    scenarioId = "standard_rental",
    algorithm = "TOPSIS",
    weightStrategy = "Expert",
    runSensitivity = false,
    requestContext = new { correlationId },
    options = new object[]
    {
        new { optionId = "OPTION-001", name = "Compact SUV Unit", values = Values(88, 91, 84, 76, 20, 26) },
        new { optionId = "OPTION-002", name = "Standard Sedan Unit", values = Values(79, 85, 92, 70, 18, 34) },
        new { optionId = "OPTION-003", name = "Premium SUV Unit", values = Values(92, 73, 68, 88, 42, 50) }
    }
};

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();
