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

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

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

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

        public CopyTradingAccountSettings? Get(int accountId)
        {
            using var ctx = _factory.CreateDbContext();
            return ctx.AccountSettings.AsNoTracking().FirstOrDefault(x => x.AccountId == accountId);
        }

        public void Upsert(CopyTradingAccountSettings settings)
        {
            using var ctx = _factory.CreateDbContext();
            var existing = ctx.AccountSettings.Find(settings.AccountId);
            if (existing == null)
                ctx.AccountSettings.Add(settings);
            else
                ctx.Entry(existing).CurrentValues.SetValues(settings);
            ctx.SaveChanges();
        }

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