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

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

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

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

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

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