using System.Text;
using HoneyBox.Admin.Data;
using HoneyBox.Admin.Services;
using HoneyBox.Core.Interfaces;
using HoneyBox.Infrastructure.Cache;
using HoneyBox.Infrastructure.External.Storage;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;

// Alias to resolve ambiguity
using AdminAuthService = HoneyBox.Admin.Services.AuthService;
using IAdminAuthService = HoneyBox.Admin.Services.IAuthService;

namespace HoneyBox.Admin.Extensions;

/// <summary>
/// 服务注册扩展方法
/// </summary>
public static class ServiceCollectionExtensions
{
    /// <summary>
    /// 添加 HoneyBox Admin 服务
    /// </summary>
    /// <param name="services">服务集合</param>
    /// <param name="configuration">配置</param>
    /// <returns>服务集合</returns>
    public static IServiceCollection AddHoneyBoxAdmin(this IServiceCollection services, IConfiguration configuration)
    {
        // 注册内存缓存（用于验证码等）
        services.AddMemoryCache();
        
        // 注册 Redis 服务（用于与小程序API共享缓存）
        services.AddSingleton<IRedisService>(sp => 
        {
            var config = sp.GetRequiredService<IConfiguration>();
            return new RedisService(config);
        });
        
        // 注册 DbContext
        services.AddDbContext<AdminDbContext>(options =>
        {
            options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
        });

        // 注册服务
        services.AddScoped<IAdminAuthService, AdminAuthService>();
        services.AddScoped<IMenuService, MenuService>();
        services.AddScoped<IRoleService, RoleService>();
        services.AddScoped<IAdminUserService, AdminUserService>();
        services.AddScoped<IDepartmentService, DepartmentService>();
        services.AddScoped<IPermissionService, PermissionService>();
        services.AddScoped<IOperationLogService, OperationLogService>();
        services.AddScoped<IDataSeeder, DataSeeder>();
        services.AddSingleton<ICaptchaService, CaptchaService>();
        
        // 注册图片上传服务（复用 Infrastructure 中的 COS 上传服务）
        services.AddScoped<IImageUploadService, CosImageUploadService>();

        // 配置 JWT 认证
        var jwtSecret = configuration["Jwt:Secret"] ?? throw new InvalidOperationException("JWT Secret not configured");
        var jwtIssuer = configuration["Jwt:Issuer"] ?? "HoneyBox.Admin";
        var jwtAudience = configuration["Jwt:Audience"] ?? "HoneyBox.Admin.Client";

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = jwtIssuer,
                ValidAudience = jwtAudience,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSecret)),
                ClockSkew = TimeSpan.Zero
            };
        });

        return services;
    }

    /// <summary>
    /// 使用 HoneyBox Admin 中间件
    /// </summary>
    /// <param name="app">应用构建器</param>
    /// <returns>应用构建器</returns>
    public static IApplicationBuilder UseHoneyBoxAdmin(this IApplicationBuilder app)
    {
        // 启用静态文件服务
        app.UseStaticFiles();

        // 启用认证 (Authorization 需要在 UseRouting 之后调用，所以不在这里调用)
        app.UseAuthentication();

        return app;
    }
}
