using CloudBuilder.Core.Application.Builders;
using CloudBuilder.Core.Application.Options;
using CloudBuilder.Core.Application.Packs;
using CloudBuilder.Core.DatabaseAccessor;
using CloudBuilder.Core.DatabaseAccessor.Entity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace CloudBuilder.Core.DependencyInjection.EFCore
{
    [PackLevel(15)]
    public class EntityFrameworkPack : CloudBuilderPack
    {
        /// <summary>
        /// 获取 模块级别
        /// </summary>
        public override PackLevel Level => PackLevel.Framework;

        /// <summary>
        /// 获取 模块启动顺序，模块启动的顺序先按级别启动，级别内部再按此顺序启动
        /// </summary>
        public override int Order => 2;

        /// <summary>
        /// 将注册实体类服务添加到依赖注入服务容器中
        /// 各模块然后自动注入实体类(含多关键字和无关键字)
        /// </summary>
        /// <param name="services">依赖注入服务容器</param>
        /// <returns></returns>
        public override IServiceCollection AddServices(IServiceCollection services, CloudBuilderBuilder builder)
        {
            var baseType = typeof(IMasterRegistEntityType<ModelBuilder>);

            var allAssemblies = CloudBuilderBuilder.GetAssemblies();

            var types = allAssemblies
                .SelectMany(a => a.DefinedTypes)
                .Select(type => type.AsType())
                .Where(type => type != baseType && baseType.IsAssignableFrom(type))
                .Where(x => x.IsClass).ToList();

            foreach (var implementType in types)
            {
                services.AddSingleton(baseType, implementType);
            }

            services.TryAddScoped(typeof(IRepository<>), typeof(Repository<>));
            services.TryAddScoped(typeof(IUnitOfWork), typeof(UnitOfWork));

            //当你直接在控制器方法上使用[UnitOfWork] 特性时，ASP.NET Core 的过滤器管道会自动实例化这个特性，不需要手动注册。
            //如果你的 UnitOfWorkAttribute 没有构造函数依赖，那么不需要注册：
            services.TryAddScoped<UnitOfWorkAttribute>();

            services.TryAddKeyedScoped<DbContext, SecondaryDbContext>(SecondaryDbContext.SECONDARY_DB_CONTEXT);
            services.TryAddKeyedScoped<DbContext, MasterDbContext>(MasterDbContext.MASTER_DB_CONTEXT);

            services.AddDbContext<SecondaryDbContext>(opts =>
        opts.UseSqlServer(builder.CloudBuilderOptions.GetDbContextOptions(SecondaryDbContext.SECONDARY_DB_CONTEXT).ConnectionString));

            services.AddDbContext<MasterDbContext>(opts =>
        opts.UseSqlServer(builder.CloudBuilderOptions.GetDbContextOptions(MasterDbContext.MASTER_DB_CONTEXT).ConnectionString));

            return services;
        }


    }
}