using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using WorkFlowCheck.DL.Interfaces;

namespace WorkFlowCheck.DL.Extensions
{
    public static class DbContextExtensions
    {
        public static void RegisterSoftDeleteQueryFilters(this ModelBuilder modelBuilder)
        {
            foreach (var entityType in modelBuilder.Model.GetEntityTypes().Where(e => typeof(ISoftDeletableEntity).IsAssignableFrom(e.ClrType)))
            {
                var parameter = Expression.Parameter(entityType.ClrType);

                var softDeletableProperty = Expression.Property(parameter, nameof(ISoftDeletableEntity.IsDeleted));
                var compareExpression = Expression.MakeBinary(ExpressionType.Equal, softDeletableProperty, Expression.Constant(false));
                var lambda = Expression.Lambda(compareExpression, parameter);

                modelBuilder.Entity(entityType.ClrType).HasQueryFilter(lambda);
            }
        }
    }
}
