using Atomx.Admin.Utils;
using Atomx.Common.Constant;
using Atomx.Common.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System.Text.Json;

namespace Atomx.Admin.Extensions
{
    public static class AuthorizationExtension
    {
        /// <summary>
        /// 添加身份验证服务
        /// </summary>
        /// <param name="services"></param>
        /// <param name="Configuration"></param>
        public static void AddAuthorize(this IServiceCollection services, IConfiguration Configuration, IWebHostEnvironment environment)
        {
            var jwtSetting = Configuration.GetSection("Authentication:JwtBearer").Get<JwtSetting>();
            if (jwtSetting == null)
            {
                throw new Exception("缺少配置信息");
            }
            services.AddSingleton(jwtSetting);

            //认证配置
            services.AddAuthentication()
                   .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
                   {
                       options.ClaimsIssuer = jwtSetting.Issuer;
                       options.RequireHttpsMetadata = !environment.IsDevelopment();   //是否要求HTTPS,生产环境建议为true
                       options.TokenValidationParameters = new TokenValidationParameters
                       {
                           ValidateIssuer = true,
                           ValidateAudience = true,
                           ValidateLifetime = true,
                           ValidateIssuerSigningKey = true,
                           ValidAudience = jwtSetting.Audience,//Audience
                           ValidIssuer = jwtSetting.Issuer,
                           ClockSkew = TimeSpan.FromMinutes(Convert.ToDouble(jwtSetting.ClockSkew)), //有效期时间偏差
                           IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSetting.SecurityKey))
                       };
                       options.Events = new JwtBearerEvents
                       {
                           // SignalR JWT支持
                           OnMessageReceived = context =>
                           {
                               //从查询字符串中获取令牌（如果存在）
                               var accessToken = context.Request.Query["access_token"];
                               var path = context.HttpContext.Request.Path;

                               if (!string.IsNullOrEmpty(accessToken) && (path.StartsWithSegments("/hubs") || path.StartsWithSegments("/notification")))
                               {
                                   context.Token = accessToken;
                               }
                               return Task.CompletedTask;
                           },

                           OnChallenge = context =>
                           {
                               var absoluteUri = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}";
                               context.HandleResponse();
                               context.Response.Redirect($"/account/login?returnUrl={Uri.EscapeDataString(absoluteUri)}");
                               return Task.CompletedTask;


                               //context.HandleResponse();
                               //context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                               //context.Response.ContentType = "application/json";

                               //var result = JsonSerializer.Serialize(new
                               //{
                               //    StatusCode = 401,
                               //    Message = "未授权访问",
                               //    Error = context.Error,
                               //    ErrorDescription = context.ErrorDescription
                               //});

                               //return context.Response.WriteAsync(result);
                           },

                           OnAuthenticationFailed = context =>
                           {
                               //Token expired
                               if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                               {
                                   context.Response.Headers.Append("Token-Expired", "true");
                               }
                               return Task.CompletedTask;
                           }

                           //OnTokenValidated = async context =>
                           //{
                           //    var userService = context.HttpContext.RequestServices.GetRequiredService<IUserService>();
                           //    var userId = context.Principal?.FindFirst("sub")?.Value;

                           //    if (userId != null)
                           //    {
                           //        var user = await userService.GetUserByIdAsync(userId);
                           //        if (user == null || !user.IsActive)
                           //        {
                           //            context.Fail("用户不存在或已被禁用");
                           //        }
                           //    }
                           //},
                       };
                   });

            services.AddAuthorization(options =>
            {
                // 基于角色的策略
                //options.AddPolicy("AdminOnly", policy =>
                //    policy.RequireRole("Administrator"));

                //options.AddPolicy("ManagerOrAdmin", policy =>
                //    policy.RequireRole("Administrator", "Manager"));

                // 基于权限的策略
                var allPermissions = Permissions.GetAllPermissions();
                foreach (var permission in allPermissions)
                {
                    options.AddPolicy(permission, policy => { policy.Requirements.Add(new PermissionRequirement(permission)); });
                }


                // 组合策略
                //options.AddPolicy("CanManageUsers", policy =>
                //{
                //    policy.RequireRole("Administrator", "UserManager");
                //    policy.Requirements.Add(new PermissionRequirement(PermissionConstants.Users.Edit));
                //});
            });



            //// HTTP客户端工厂
            //services.AddHttpClient("ApiClient")
            //    .AddTransientHttpErrorPolicy(policy =>
            //        policy.WaitAndRetryAsync(3, retryAttempt =>
            //            TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))))
            //    .AddTransientHttpErrorPolicy(policy =>
            //        policy.CircuitBreakerAsync(5, TimeSpan.FromSeconds(30)));


            //// API版本控制
            //services.AddApiVersioning(options =>
            //{
            //    options.DefaultApiVersion = new Microsoft.AspNetCore.Mvc.ApiVersion(1, 0);
            //    options.AssumeDefaultVersionWhenUnspecified = true;
            //    options.ReportApiVersions = true;
            //});


            //// 添加响应压缩
            //services.AddResponseCompression(options =>
            //{
            //    options.EnableForHttps = true;
            //    options.Providers.Add<BrotliCompressionProvider>();
            //    options.Providers.Add<GzipCompressionProvider>();
            //});
        }
    }
}
