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

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

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

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

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

        public List<TradeRecord> GetRecent(int limit)
        {
            using var ctx = _factory.CreateDbContext();
            return ctx.TradeLog.AsNoTracking().OrderByDescending(x => x.ClosedAt).Take(limit).ToList();
        }

        public List<TradeRecord> Find(Expression<Func<TradeRecord, bool>> predicate)
        {
            using var ctx = _factory.CreateDbContext();
            return ctx.TradeLog.AsNoTracking().Where(predicate).ToList();
        }
    }
}
