using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Reflection;
using Domain;
using Domain.Identity;
using Infrastructure;
using Domain.BaseData;

namespace Core.Db
{
    public class PanakDbContext : DbContext
    {

        public PanakDbContext(DbContextOptions options) : base(options)
        {

        }

        public DbSet<Account> Accounts { get; set; }
        public DbSet<Role> Roles { get; set; }
        public DbSet<AccountRole> AccountRoles { get; set; }
        public DbSet<LoginToken> LoginTokens { get; set; }
        public DbSet<RefreshToken> RefreshTokens { get; set; }

        #region ThisProject
        public DbSet<Plant> Plants { get; set; }


        #endregion



        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {

            modelBuilder.Entity<LoginToken>()
                .HasOne(x => x.RefreshToken)
                .WithOne(a => a.LoginToken)
                .HasForeignKey<RefreshToken>(x => x.LoginTokenId);
          

         
            modelBuilder.Entity<Role>().HasData(
                new Role { Name = Consts.AdminRole },
                new Role { Name = Consts.Developer }
            );
            base.OnModelCreating(modelBuilder);
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseLazyLoadingProxies();
            base.OnConfiguring(optionsBuilder);
        }

    }

    public static class EFFilterExtensions
    {
        public static void ApplySoftDeleteFilter(this ModelBuilder modelBuilder, Type entityType)
        {
            SetSoftDeleteFilterMethod.MakeGenericMethod(entityType).Invoke(null, new object[] { modelBuilder });
        }

        static readonly MethodInfo SetSoftDeleteFilterMethod = typeof(EFFilterExtensions)
                   .GetMethods(BindingFlags.Public | BindingFlags.Static)
                   .Single(t => t.IsGenericMethod && t.Name == "ApplySoftDeleteFilter");

        public static void ApplySoftDeleteFilter<TEntity>(this ModelBuilder modelBuilder) where TEntity : BaseEntity
        {
            modelBuilder.Entity<TEntity>().HasQueryFilter(x => !x.Deleted);
        }
    }

}
