using System.Linq;
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 Demo-Einstiegs: akzeptierte Kandidaten → geplante/geöffnete rf_positions.</summary>
    public class FarmingExecutionServiceTests
    {
        private static RfSettings Settings() => new()
        {
            AccountId = 1, MaxPerMarketUsd = 25m, MaxPerClusterPct = 10m, MaxTotalExposurePct = 60m,
            MaxNewPositionsPerDay = 20, DailyLossKillSwitchUsd = 0m
        };

        private static (FarmingExecutionService svc, EfRfPositionRepository posRepo, EfRfCandidateRepository candRepo) Build()
        {
            var factory = new InMemoryContextFactory<ResolutionFarmingDbContext>(o => new ResolutionFarmingDbContext(o));
            var candRepo = new EfRfCandidateRepository(factory);
            var posRepo = new EfRfPositionRepository(factory);
            var closedRepo = new EfRfClosedTradeRepository(factory);
            var settingsRepo = new EfRfSettingsRepository(factory);
            var svc = new FarmingExecutionService(new TradingState(), settingsRepo, candRepo, posRepo, closedRepo, new TerminalLogger(), new FakeDecisionJournal());
            return (svc, posRepo, candRepo);
        }

        [Fact]
        public void RunDemo_opens_positions_for_accepted_candidates()
        {
            var (svc, posRepo, candRepo) = Build();
            candRepo.Insert(new RfCandidate { AccountId = 1, Accepted = true, TokenId = "a", ClusterKey = "c1", Ask = 0.95m, Score = 5m });
            candRepo.Insert(new RfCandidate { AccountId = 1, Accepted = true, TokenId = "b", ClusterKey = "c2", Ask = 0.95m, Score = 3m });
            candRepo.Insert(new RfCandidate { AccountId = 1, Accepted = false, TokenId = "z", ClusterKey = "c3", Ask = 0.80m, Score = 9m }); // abgelehnt -> ignoriert

            var opened = svc.RunDemoForAccount(1, bankrollUsd: 1000m, Settings());

            Assert.Equal(2, opened.Count);
            var stored = posRepo.GetOpen(1);
            Assert.Equal(2, stored.Count);
            var a = stored.First(p => p.TokenId == "a");
            Assert.Equal(0.95m, a.EntryPrice);
            Assert.Equal(26.31m, a.Size);          // floor(25/0.95, 2 Dez.)
            Assert.Equal(24.9945m, a.AmountUsd);   // Maker (0 Fee): shares * ask
            Assert.True(a.IsDemo);
            Assert.Equal("Open", a.Status);
        }

        [Fact]
        public void RunDemo_skips_already_held_market()
        {
            var (svc, posRepo, candRepo) = Build();
            posRepo.Upsert(new RfPosition { AccountId = 1, TokenId = "a", ClusterKey = "c1", AmountUsd = 20m });
            candRepo.Insert(new RfCandidate { AccountId = 1, Accepted = true, TokenId = "a", ClusterKey = "c1", Ask = 0.95m, Score = 9m });
            candRepo.Insert(new RfCandidate { AccountId = 1, Accepted = true, TokenId = "b", ClusterKey = "c2", Ask = 0.95m, Score = 3m });

            var opened = svc.RunDemoForAccount(1, 1000m, Settings());

            Assert.Single(opened);
            Assert.Equal("b", opened[0].TokenId);
        }
    }
}
