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

namespace PolyTrader.Modules.CopyTrading.Persistence.Ef
{
    public class EfMasterTraderHistoryRepository : IMasterTraderHistoryRepository
    {
        private readonly IDbContextFactory<CopyTradingDbContext> _factory;

        public EfMasterTraderHistoryRepository(IDbContextFactory<CopyTradingDbContext> factory) => _factory = factory;

        public void EnsureIndexes() { }

        public bool Exists(int traderId, string tokenId, DateTime windowStart, DateTime windowEnd)
        {
            using var ctx = _factory.CreateDbContext();
            return ctx.History.AsNoTracking().Any(x => x.TraderId == traderId && x.TokenId == tokenId
                && x.ClosedAt >= windowStart && x.ClosedAt <= windowEnd);
        }

        public void Insert(MasterTraderHistoryRecord record)
        {
            using var ctx = _factory.CreateDbContext();
            ctx.History.Add(record);
            ctx.SaveChanges();
        }

        public List<MasterTraderHistoryRecord> GetByTraderSince(int traderId, DateTime since)
        {
            using var ctx = _factory.CreateDbContext();
            return ctx.History.AsNoTracking().Where(x => x.TraderId == traderId && x.ClosedAt >= since).ToList();
        }
    }
}
