using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Predictalytics.Domain.Entities;
using Predictalytics.Domain.Enums;
using Predictalytics.Infrastructure.Data;
using Predictalytics.Infrastructure.Services;
using Predictalytics.Worker.Services;
using Xunit;

namespace Predictalytics.Application.Tests.Services;

/// <summary>
/// Invariant tests for the retention/compaction worker (added 2026-07-09).
/// Uses SQLite in-memory instead of the InMemory provider because the worker
/// relies on ExecuteDeleteAsync/ExecuteUpdateAsync (relational-only).
/// </summary>
public class TradeRetentionWorkerTests
{
    /// <summary>
    /// Defect 2: Compaction bumps the position checkpoint to the aggregate
    /// trade's Id — which is the highest Id in the table. Any UNAPPLIED real
    /// trade with a smaller Id silently falls below the checkpoint and is never
    /// booked (IsHistoryPruned additionally blocks the reset self-heal).
    ///
    /// Invariant: after compaction plus a PnL engine run, every previously
    /// unapplied trade must be reflected in the position. Valid fixes include
    /// skipping compaction while unapplied trades exist for the position, or
    /// marking the aggregate as pre-applied without moving the checkpoint past
    /// unapplied trades. EXPECTED TO BE RED until fixed.
    /// </summary>
    [Fact]
    public async Task RunOptimizationAsync_CompactionWithUnappliedTrades_DoesNotLoseThem()
    {
        // ── Arrange: shared SQLite in-memory database ────────────────────────
        using var connection = new SqliteConnection("DataSource=:memory:");
        connection.Open();
        var options = new DbContextOptionsBuilder<AppDbContext>()
            .UseSqlite(connection)
            .Options;

        var baseDate = DateTime.UtcNow.Date;

        using (var setup = new AppDbContext(options))
        {
            setup.Database.EnsureCreated();

            var ev = new Event { Id = 1, Platform = PlatformType.Polymarket, Slug = "e", Title = "E" };
            setup.Set<Event>().Add(ev);

            var market = new Market { Id = 10, EventId = 1, PlatformMarketId = 1L, Question = "Q?" };
            market.Outcomes.Add(new MarketOutcome { Id = 100, MarketId = 10, Label = "Yes", TokenId = "t100", CurrentPrice = 0.45m });
            setup.Markets.Add(market);

            // Bot trader → target of the compaction pass.
            setup.Traders.Add(new Trader { Id = 1, PlatformUserId = "0x1", DisplayName = "Bot", IsSuspectedBot = true });

            // Two APPLIED trades, older than the compaction cutoff, same day/side
            // → they form a compactable group.
            setup.Trades.Add(new Trade
            {
                Id = 10, TraderId = 1, DbMarketId = 10, MarketOutcomeId = 100, PlatformTradeId = "tx10",
                Side = TradeSide.Buy, Price = 0.40m, Size = 50m, Amount = 20m,
                ExecutedAt = baseDate.AddDays(-20).AddHours(10)
            });
            setup.Trades.Add(new Trade
            {
                Id = 11, TraderId = 1, DbMarketId = 10, MarketOutcomeId = 100, PlatformTradeId = "tx11",
                Side = TradeSide.Buy, Price = 0.40m, Size = 50m, Amount = 20m,
                ExecutedAt = baseDate.AddDays(-20).AddHours(11)
            });

            // One UNAPPLIED trade (imported but not yet analyzed): Id 12 is above
            // the checkpoint (11) but below the aggregate's future Id.
            setup.Trades.Add(new Trade
            {
                Id = 12, TraderId = 1, DbMarketId = 10, MarketOutcomeId = 100, PlatformTradeId = "tx12",
                Side = TradeSide.Buy, Price = 0.50m, Size = 100m, Amount = 50m,
                ExecutedAt = baseDate.AddDays(-5).AddHours(10)
            });

            // Position reflects exactly the two applied trades.
            setup.TraderPositions.Add(new TraderPosition
            {
                Id = 1, TraderId = 1, MarketOutcomeId = 100,
                SharesHeld = 100m, AvgCost = 0.40m, RealizedPnl = 0m,
                LastAppliedTradeId = 11,
                LastTradeExecutedAt = baseDate.AddDays(-20).AddHours(11),
                IsHistoryPruned = false
            });

            setup.SaveChanges();
        }

        var services = new ServiceCollection();
        services.AddScoped(_ => new AppDbContext(options));
        using var provider = services.BuildServiceProvider();

        var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
        {
            ["RetentionSettings:RetentionDays"] = "90",
            ["RetentionSettings:CompactionDays"] = "14"
        }).Build();

        var worker = new TradeRetentionWorker(provider, config, NullLogger<TradeRetentionWorker>.Instance);

        // RunOptimizationAsync is private; invoked via reflection on purpose so
        // this test exercises the real production code path. Making the method
        // internal (+ InternalsVisibleTo) instead of this reflection call is a
        // welcome refactor.
        var method = typeof(TradeRetentionWorker).GetMethod("RunOptimizationAsync", BindingFlags.Instance | BindingFlags.NonPublic);
        Assert.NotNull(method);

        // ── Act 1: retention/compaction pass ─────────────────────────────────
        await (Task)method!.Invoke(worker, new object[] { CancellationToken.None })!;

        // ── Act 2: next analytics run ────────────────────────────────────────
        using (var engineCtx = new AppDbContext(options))
        {
            var engine = new PositionPnLEngine(engineCtx, NullLogger<PositionPnLEngine>.Instance);
            await engine.RecalculateTraderPositionsAsync(1);
        }

        // ── Assert: the unapplied trade (Id 12) must now be part of the position:
        // 100 shares @0.40 (compacted or not) + 100 shares @0.50 → 200 @ 0.45.
        using (var assertCtx = new AppDbContext(options))
        {
            var pos = await assertCtx.TraderPositions.SingleAsync(p => p.TraderId == 1 && p.MarketOutcomeId == 100);
            Assert.Equal(200m, pos.SharesHeld);
            Assert.Equal(0.45m, pos.AvgCost);
        }
    }

    [Fact]
    public async Task RunOptimizationAsync_PrunesAggregatedTraderTrades()
    {
        using var connection = new SqliteConnection("DataSource=:memory:");
        connection.Open();
        var options = new DbContextOptionsBuilder<AppDbContext>()
            .UseSqlite(connection)
            .Options;

        var baseDate = DateTime.UtcNow.Date;

        using (var setup = new AppDbContext(options))
        {
            setup.Database.EnsureCreated();

            var ev = new Event { Id = 1, Platform = PlatformType.Polymarket, Slug = "e", Title = "E" };
            setup.Set<Event>().Add(ev);

            var market = new Market { Id = 10, EventId = 1, PlatformMarketId = 1L, Question = "Q?" };
            market.Outcomes.Add(new MarketOutcome { Id = 100, MarketId = 10, Label = "Yes", TokenId = "t100", CurrentPrice = 0.45m });
            setup.Markets.Add(market);

            // Aggregated trader - target of G2 retention pruning
            setup.Traders.Add(new Trader { Id = 2, PlatformUserId = "0x2", DisplayName = "AggregatedTrader", IngestMode = IngestMode.Aggregated });

            // Old trade older than retention cut-off (e.g. 200 days old when retention is 90 days)
            setup.Trades.Add(new Trade
            {
                Id = 20, TraderId = 2, DbMarketId = 10, MarketOutcomeId = 100, PlatformTradeId = "tx20",
                Side = TradeSide.Buy, Price = 0.40m, Size = 50m, Amount = 20m,
                ExecutedAt = baseDate.AddDays(-200)
            });

            setup.SaveChanges();
        }

        var services = new ServiceCollection();
        services.AddScoped(_ => new AppDbContext(options));
        using var provider = services.BuildServiceProvider();

        var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
        {
            ["RetentionSettings:RetentionDays"] = "90",
            ["RetentionSettings:CompactionDays"] = "14",
            ["RetentionSettings:MaxDatabaseSizeGb"] = "90.0",
            ["RetentionSettings:MinRetentionDays"] = "30"
        }).Build();

        var worker = new TradeRetentionWorker(provider, config, NullLogger<TradeRetentionWorker>.Instance);
        var method = typeof(TradeRetentionWorker).GetMethod("RunOptimizationAsync", BindingFlags.Instance | BindingFlags.NonPublic);
        Assert.NotNull(method);

        // Act: Run optimization
        await (Task)method!.Invoke(worker, new object[] { CancellationToken.None })!;

        // Assert: The old trade must be deleted
        using (var assertCtx = new AppDbContext(options))
        {
            var oldTradeExists = await assertCtx.Trades.AnyAsync(t => t.Id == 20);
            Assert.False(oldTradeExists, "The old trade of the Aggregated trader should have been pruned.");
        }
    }
}
