using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;
using Dapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using QuantEngine.Infrastructure.Data;
using QuantEngine.Web.Services;

namespace QuantEngine.Web.Pages.Admin.Decisions;

[Authorize(AuthenticationSchemes = AdminAuthDefaults.Scheme)]
public class DetailModel : PageModel
{
    private readonly IDbConnectionFactory _connectionFactory;

    public IDictionary<string, object?>? Decision { get; private set; }
    public JsonElement ProvenanceJson { get; private set; }

    public DetailModel(IDbConnectionFactory connectionFactory)
    {
        _connectionFactory = connectionFactory;
    }

    public async Task<IActionResult> OnGetAsync(long id)
    {
        using var conn = _connectionFactory.CreateConnection();
        conn.Open();

        var row = await conn.QueryFirstOrDefaultAsync(@"
            SELECT id, decision_id, decided_at, instrument_id, action, gate, score, source_version, provenance, created_at
            FROM engine_history.decision_result_history
            WHERE id = @Id", new { Id = id });

        if (row == null)
        {
            return RedirectToPage("/Admin/Decisions/Index");
        }

        Decision = (IDictionary<string, object?>)row;

        string provenanceStr = row.provenance?.ToString() ?? "{}";
        try
        {
            ProvenanceJson = JsonDocument.Parse(provenanceStr).RootElement;
        }
        catch
        {
            ProvenanceJson = JsonDocument.Parse("{}").RootElement;
        }

        return Page();
    }
}
