using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using PolyTraderSharp.Models;

namespace PolyTrader.Core.Persistence.Ef
{
    public class EfMarketRepository : IMarketRepository
    {
        private readonly IDbContextFactory<CoreDbContext> _factory;

        public EfMarketRepository(IDbContextFactory<CoreDbContext> factory) => _factory = factory;

        public MarketData? GetById(string id)
        {
            using var ctx = _factory.CreateDbContext();
            return ctx.Markets.AsNoTracking().FirstOrDefault(x => x.Id == id);
        }

        public MarketData? FindByTokenId(string tokenId)
        {
            using var ctx = _factory.CreateDbContext();
            return ctx.Markets.AsNoTracking()
                .FirstOrDefault(x => x.ClobTokenIds != null && x.ClobTokenIds.Contains(tokenId));
        }

        public List<MarketData> GetActive()
        {
            using var ctx = _factory.CreateDbContext();
            return ctx.Markets.AsNoTracking().Where(x => !x.Closed).ToList();
        }

        public void Upsert(MarketData market)
        {
            using var ctx = _factory.CreateDbContext();
            var existing = ctx.Markets.Find(market.Id);
            if (existing == null)
                ctx.Markets.Add(market);
            else
                ctx.Entry(existing).CurrentValues.SetValues(market);
            ctx.SaveChanges();
        }

        public void Insert(MarketData market)
        {
            using var ctx = _factory.CreateDbContext();
            ctx.Markets.Add(market);
            ctx.SaveChanges();
        }

        public void Update(MarketData market)
        {
            using var ctx = _factory.CreateDbContext();
            var existing = ctx.Markets.Find(market.Id);
            if (existing != null)
            {
                ctx.Entry(existing).CurrentValues.SetValues(market);
                ctx.SaveChanges();
            }
        }

        // Indizes werden über die EF-Migration erstellt.
        public void EnsureIndexes() { }
    }
}
