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

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

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

        public List<TrackedTrader> GetAll()
        {
            using var ctx = _factory.CreateDbContext();
            return ctx.Traders.AsNoTracking().ToList();
        }

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

        public void Update(TrackedTrader trader) => Upsert(trader);

        public void Delete(int id)
        {
            using var ctx = _factory.CreateDbContext();
            var existing = ctx.Traders.Find(id);
            if (existing != null)
            {
                ctx.Traders.Remove(existing);
                ctx.SaveChanges();
            }
        }
    }
}
