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-ins-011-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 tokenJson = await tokenResponse.Content.ReadAsStringAsync();
var jwtToken = JsonDocument.Parse(tokenJson).RootElement.GetProperty("jwtToken").GetString();

using var metadataRequest = new HttpRequestMessage(HttpMethod.Get, $"{catalogUrl}/decisioncatalog/decisions/AUTO-INS-011");
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-INS-011",
    profileId = "balanced",
    scenarioId = "standard",
    algorithm = "TOPSIS",
    weightStrategy = "Expert",
    runSensitivity = false,
    requestContext = new { correlationId },
    options = new object[]
    {
        new
        {
            optionId = "CLAIM-011-01",
            name = "Claim CASE-001",
            values = new Dictionary<string, double>
            {
                ["claim_severity_score"] = 83,
                ["customer_impact_score"] = 83,
                ["coverage_clarity_score"] = 83,
                ["fraud_risk_score"] = 78,
                ["estimated_loss_amount"] = 62500
            }
        },
        new
        {
            optionId = "CLAIM-011-02",
            name = "Claim CASE-002",
            values = new Dictionary<string, double>
            {
                ["claim_severity_score"] = 75,
                ["customer_impact_score"] = 75,
                ["coverage_clarity_score"] = 75,
                ["fraud_risk_score"] = 70,
                ["estimated_loss_amount"] = 107500
            }
        }
    }
};

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