using System;
using System.Linq;
using PolyTrader.Modules.CopyTrading.Persistence.Ef;
using PolyTrader.Tests.TestSupport;
using PolyTraderSharp.Models;
using Xunit;

namespace PolyTrader.Tests
{
    public class MasterTraderHistoryRepositoryTests
    {
        private static EfMasterTraderHistoryRepository NewRepo() =>
            new(new InMemoryContextFactory<CopyTradingDbContext>(o => new CopyTradingDbContext(o)));

        [Fact]
        public void Exists_is_true_within_time_window()
        {
            var repo = NewRepo();
            var t = new DateTime(2026, 7, 1, 12, 0, 0, DateTimeKind.Utc);
            repo.Insert(new MasterTraderHistoryRecord { TraderId = 1, TokenId = "tok", ClosedAt = t, RealizedPnl = 5m });

            Assert.True(repo.Exists(1, "tok", t.AddSeconds(-2), t.AddSeconds(2)));
        }

        [Fact]
        public void Exists_is_false_outside_window_or_wrong_trader()
        {
            var repo = NewRepo();
            var t = new DateTime(2026, 7, 1, 12, 0, 0, DateTimeKind.Utc);
            repo.Insert(new MasterTraderHistoryRecord { TraderId = 1, TokenId = "tok", ClosedAt = t });

            Assert.False(repo.Exists(1, "tok", t.AddMinutes(1), t.AddMinutes(2)));
            Assert.False(repo.Exists(2, "tok", t.AddSeconds(-2), t.AddSeconds(2)));
            Assert.False(repo.Exists(1, "nope", t.AddSeconds(-2), t.AddSeconds(2)));
        }

        [Fact]
        public void GetByTraderSince_filters_by_trader_and_cutoff()
        {
            var repo = NewRepo();
            var now = new DateTime(2026, 7, 8, 0, 0, 0, DateTimeKind.Utc);
            repo.Insert(new MasterTraderHistoryRecord { TraderId = 1, ClosedAt = now.AddDays(-1) });   // in
            repo.Insert(new MasterTraderHistoryRecord { TraderId = 1, ClosedAt = now.AddDays(-10) });  // too old
            repo.Insert(new MasterTraderHistoryRecord { TraderId = 2, ClosedAt = now });               // other trader

            var result = repo.GetByTraderSince(1, now.AddDays(-7));

            Assert.Single(result);
            Assert.Equal(1, result[0].TraderId);
        }
    }
}
