namespace HiVakil.Repository.Repositories.Base
{
    public class ReadRepository<T> : Repository<T>, IDisposable, IReadRepository<T> where T : class, IApiEntity
    {
        public ReadRepository(
            ApplicationContext dbContext) : base(dbContext)
        {
        }

        public new void Dispose()
        {
            DbContext?.Dispose();
        }


        public virtual T GetById(params object[] ids)
        {
            var ent = Entities.Find(ids);
            if (ent == null)
                throw new AppException("Ent not found");
            Detach(ent);
            return ent;
        }

        public virtual ValueTask<T> GetByIdAsync(CancellationToken cancellationToken, params object[] ids)
        {
            return Entities.FindAsync(ids, cancellationToken);
        }

        public virtual void Detach(T entity)
        {
            AssertExtensions.NotNull(entity, nameof(entity));
            var entry = DbContext.Entry(entity);
            entry.State = EntityState.Detached;
        }

        public virtual void Attach(T entity)
        {
            AssertExtensions.NotNull(entity, nameof(entity));
            if (DbContext.Entry(entity).State == EntityState.Detached)
                Entities.Attach(entity);
        }
    }
}