using Dollet.Core.Abstractions;
using Dollet.Core.Abstractions.Repositories;
using Microsoft.EntityFrameworkCore;

namespace Dollet.Infrastructure.DAL
{
    internal class UnitOfWork(DolletDbContext dbContext, Lazy<IAccountRepository> accountRepository,
        Lazy<IAppDataRepository> appDataRepository, Lazy<ICategoryRepository> categoryRepository,
        Lazy<ICurrencyRepository> currencyRepository, Lazy<IExpensesRepository> expensesRepository,
        Lazy<IIncomesRepository> incomesRepository) : IUnitOfWork
    {
        private readonly DolletDbContext _dbContext = dbContext;
        private readonly Lazy<IAccountRepository> _accountRepository = accountRepository;
        private readonly Lazy<IAppDataRepository> _appDataRepository = appDataRepository;
        private readonly Lazy<ICategoryRepository> _categoryRepository = categoryRepository;
        private readonly Lazy<ICurrencyRepository> _currencyRepository = currencyRepository;
        private readonly Lazy<IExpensesRepository> _expensesRepository = expensesRepository;
        private readonly Lazy<IIncomesRepository> _incomesRepository = incomesRepository;

        public IAccountRepository AccountRepository => _accountRepository.Value;
        public IAppDataRepository AppDataRepository => _appDataRepository.Value;
        public ICategoryRepository CategoryRepository => _categoryRepository.Value;
        public ICurrencyRepository CurrencyRepository => _currencyRepository.Value;
        public IExpensesRepository ExpensesRepository => _expensesRepository.Value;
        public IIncomesRepository IncomesRepository => _incomesRepository.Value;

        public async Task<bool> CommitAsync()
        {
            var saved = await _dbContext.SaveChangesAsync() > 0;

            foreach(var entry in _dbContext.ChangeTracker.Entries().ToArray())
            {
                entry.State = EntityState.Detached;
            }

            return saved;
        }
    }
}