using System.Reflection;
using Microsoft.Extensions.DependencyInjection;

namespace Common;

/// <summary>
/// 服务依赖注入扩展
/// </summary>
public static class ServiceExtension
{
    /// <summary>
    /// 自动扫描并注册服务和仓储
    /// </summary>
    public static IServiceCollection AddServices(this IServiceCollection services)
    {
        // 扫描程序集
        var serviceAssembly = Assembly.Load("Service");
        var repositoryAssembly = Assembly.Load("Repository");

        // 注册所有服务实现
        RegisterServices(services, serviceAssembly);
        
        // 注册所有仓储实现
        RegisterRepositories(services, repositoryAssembly);

        return services;
    }

    private static void RegisterServices(IServiceCollection services, Assembly assembly)
    {
        var types = assembly.GetTypes()
            .Where(t => t.IsClass && !t.IsAbstract);

        foreach (var type in types)
        {
            var interfaces = type.GetInterfaces()
                .Where(i => i.Name.StartsWith("I") && i.Namespace != null && i.Namespace.StartsWith("Service"));

            foreach (var @interface in interfaces)
            {
                // EmailBackgroundService 必须是 Singleton（后台服务），其他服务可用 Transient
                if (type.Name == "EmailBackgroundService")
                {
                    services.AddSingleton(@interface, type);
                }
                else if (type.Name == "EmailFetchService")
                {
                    // EmailFetchService 用 Transient，避免连接冲突
                    services.AddTransient(@interface, type);
                }
                else
                {
                    services.AddSingleton(@interface, type);
                }
            }
        }
    }

    private static void RegisterRepositories(IServiceCollection services, Assembly assembly)
    {
        var types = assembly.GetTypes()
            .Where(t => t.IsClass && !t.IsAbstract);

        foreach (var type in types)
        {
            var interfaces = type.GetInterfaces()
                .Where(i => i.Name.StartsWith("I") 
                         && i.Namespace == "Repository"
                         && !i.IsGenericType); // 排除泛型接口如 IBaseRepository<T>

            foreach (var @interface in interfaces)
            {
                services.AddSingleton(@interface, type);
                Console.WriteLine($"注册 Repository: {@interface.Name} -> {type.Name}");
            }
        }
    }
}

