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

namespace PolyTrader.Tests
{
    public class MarketRepositoryTests
    {
        private static EfMarketRepository NewRepo() =>
            new(new InMemoryContextFactory<CoreDbContext>(o => new CoreDbContext(o)));

        [Fact]
        public void GetActive_returns_only_non_closed_markets()
        {
            var repo = NewRepo();
            repo.Upsert(new MarketData { Id = "m1", Closed = false });
            repo.Upsert(new MarketData { Id = "m2", Closed = true });

            var active = repo.GetActive();
            Assert.Single(active);
            Assert.Equal("m1", active[0].Id);
        }

        [Fact]
        public void Upsert_updates_existing_market()
        {
            var repo = NewRepo();
            repo.Upsert(new MarketData { Id = "m1", Question = "old" });
            repo.Upsert(new MarketData { Id = "m1", Question = "new" });

            Assert.Equal("new", repo.GetById("m1")!.Question);
        }

        [Fact]
        public void FindByTokenId_matches_within_clob_token_ids()
        {
            var repo = NewRepo();
            repo.Upsert(new MarketData { Id = "m1", ClobTokenIds = "[\"abc\",\"def\"]" });

            Assert.Equal("m1", repo.FindByTokenId("def")!.Id);
            Assert.Null(repo.FindByTokenId("zzz"));
        }
    }
}
