using QuantEngine.Infrastructure.Repositories;
using Xunit;

namespace QuantEngine.Core.Tests;

/// <summary>
/// Unit test suite serving as the primary automated harness for PostgreSQL History Store.
/// Strictly verifies Dapper SQL generation, 3NF schema binding, and unit test level correctness.
/// </summary>
public class PostgresqlHistoryStoreTests
{
    [Fact]
    public void DomainColumnsExposeCanonicalDomains()
    {
        var domains = PostgresqlHistoryStore.GetDomainColumns();

        Assert.Contains("decision_result_history", domains.Keys);
        Assert.Contains("factor_output_history", domains.Keys);
        Assert.Contains("market_raw_history", domains.Keys);
        Assert.Contains("market_vs_engine_gap_history", domains.Keys);
        Assert.True(domains["decision_result_history"].Contains("decision_id"));
        Assert.True(domains["factor_output_history"].Contains("output_gate"));
    }

    [Fact]
    public void BuildInsertSqlUsesEngineHistoryPrefixAndNamedParameters()
    {
        var sql = PostgresqlHistoryStore.BuildInsertSql(
            "decision_result_history",
            new[] { "decision_id", "decided_at", "instrument_id", "action", "gate", "score", "source_version", "provenance" });

        Assert.Equal(
            "INSERT INTO engine_history.decision_result_history (decision_id, decided_at, instrument_id, action, gate, score, source_version, provenance) VALUES (@decision_id, @decided_at, @instrument_id, @action, @gate, @score, @source_version, CAST(@provenance AS jsonb))",
            sql);
    }

    [Fact]
    public void BuildSnapshotSqlUsesCreatedAtDescendingAndLimitParameter()
    {
        var sql = PostgresqlHistoryStore.BuildSnapshotSql("factor_output_history", 25);

        Assert.Equal(
            "SELECT * FROM engine_history.factor_output_history ORDER BY created_at DESC LIMIT @Limit",
            sql);
    }

    [Fact]
    public void VerifyWaterfallAndShadowLedgerSchemaIntegrity()
    {
        // Unit test harness enforcing exact schema and parameter contract for Waterfall & Shadow Ledger
        var repoType = typeof(PostgresqlHistoryStore);
        var waterfallMethod = repoType.GetMethod(nameof(PostgresqlHistoryStore.RecordWaterfallExecutionAsync));
        var shadowMethod = repoType.GetMethod(nameof(PostgresqlHistoryStore.RecordShadowLedgerAsync));

        Assert.NotNull(waterfallMethod);
        Assert.NotNull(shadowMethod);
        Assert.Equal(11, waterfallMethod.GetParameters().Length);
        Assert.Equal(8, shadowMethod.GetParameters().Length);
    }
}
