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

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

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

        public void EnsureIndexes() { }

        public bool Exists(int accountId, string tokenId)
        {
            using var ctx = _factory.CreateDbContext();
            return ctx.ClosedTrades.AsNoTracking().Any(x => x.AccountId == accountId && x.TokenId == tokenId);
        }

        public void Insert(ClosedTrade trade)
        {
            using var ctx = _factory.CreateDbContext();
            ctx.ClosedTrades.Add(trade);
            ctx.SaveChanges();
        }

        public int GetMaxTradeId()
        {
            using var ctx = _factory.CreateDbContext();
            // Serverseitiges MAX statt Laden der gesamten Tabelle. Nullable-Cast, damit leere Tabelle 0 gibt.
            return ctx.ClosedTrades.AsNoTracking().Max(x => (int?)x.TradeId) ?? 0;
        }

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