using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using PolyTrader.Modules.ResolutionFarming.Models;
using PolyTrader.Modules.ResolutionFarming.Persistence.Ef;
using PolyTrader.Modules.ResolutionFarming.Services;
using PolyTrader.Tests.Fakes;
using PolyTrader.Tests.TestSupport;
using PolyTraderSharp;
using PolyTraderSharp.Services;
using Xunit;

namespace PolyTrader.Tests
{
    /// <summary>Orchestrierungstest des Resolution-Monitors: aufgelöste Positionen werden geschlossen, gebucht und dual-geschrieben.</summary>
    public class FarmingResolutionMonitorTests
    {
        private sealed class FakeResolution : IMarketResolutionSource
        {
            private readonly Dictionary<string, (bool, bool)> _byToken;
            public FakeResolution(Dictionary<string, (bool, bool)> byToken) => _byToken = byToken;
            public Task<(bool isClosed, bool isWinner)> CheckAsync(string slug, string tokenId, CancellationToken ct)
                => Task.FromResult(_byToken.TryGetValue(tokenId, out var r) ? r : (false, false));
        }

        [Fact]
        public async Task Closes_resolved_winner_and_dual_writes()
        {
            var factory = new InMemoryContextFactory<ResolutionFarmingDbContext>(o => new ResolutionFarmingDbContext(o));
            var posRepo = new EfRfPositionRepository(factory);
            var closedRepo = new EfRfClosedTradeRepository(factory);
            posRepo.Upsert(new RfPosition { AccountId = 1, TokenId = "a", MarketSlug = "m-a", Size = 100m, EntryPrice = 0.95m, AmountUsd = 95m, EntryFeeBps = 0, IsDemo = true });
            posRepo.Upsert(new RfPosition { AccountId = 1, TokenId = "b", MarketSlug = "m-b", Size = 50m, EntryPrice = 0.90m, AmountUsd = 45m, EntryFeeBps = 0, IsDemo = true });

            var resolution = new FakeResolution(new() { ["a"] = (true, true) }); // nur a aufgelöst (Gewinner)
            var coreLog = new FakeCoreTradeLogRepository();
            var state = new TradingState();
            var svc = new FarmingResolutionMonitorService(state, posRepo, closedRepo, resolution, coreLog, new TerminalLogger(), new FakeDecisionJournal());

            var closed = await svc.CheckAndCloseAsync(CancellationToken.None);

            Assert.Single(closed);
            Assert.Equal(5m, closed[0].RealizedPnl);                 // 100 - 95
            Assert.Equal(5m, state.GlobalPnl);                       // fortgeschrieben
            Assert.Null(posRepo.Find(1, "a"));                       // Position entfernt
            Assert.NotNull(posRepo.Find(1, "b"));                    // b bleibt offen (nicht aufgelöst)
            Assert.Single(closedRepo.Find(t => t.AccountId == 1));
            Assert.Single(coreLog.Inserted);                         // Dual-Write ins Core-Log
            Assert.Equal("ResolutionFarming", coreLog.Inserted[0].ModuleName);
        }

        [Fact]
        public async Task Leaves_unresolved_positions_open()
        {
            var factory = new InMemoryContextFactory<ResolutionFarmingDbContext>(o => new ResolutionFarmingDbContext(o));
            var posRepo = new EfRfPositionRepository(factory);
            var closedRepo = new EfRfClosedTradeRepository(factory);
            posRepo.Upsert(new RfPosition { AccountId = 1, TokenId = "a", MarketSlug = "m-a", Size = 100m, EntryPrice = 0.95m, AmountUsd = 95m });

            var svc = new FarmingResolutionMonitorService(new TradingState(), posRepo, closedRepo,
                new FakeResolution(new()), new FakeCoreTradeLogRepository(), new TerminalLogger(), new FakeDecisionJournal());

            var closed = await svc.CheckAndCloseAsync(CancellationToken.None);

            Assert.Empty(closed);
            Assert.NotNull(posRepo.Find(1, "a"));
        }
    }
}
