using Lada.Framework.Data.Domains.Identity;
using Lada.Framework.Data.Mappings.DbContexts;
using Lada.Framework.Infrastructures.AppSettings;
using Ladaer.BackEnd.Infrastructures.AppSettings;
using Ladaer.BackEnd.Infrastructures.Authorization;
using Ladaer.BackEnd.Infrastructures.IdentityConfigs;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;
using System.Text;

namespace Ladaer.BackEnd.Infrastructures.Startup
{
    /// <summary>
    /// Lớp mở rộng để đăng ký các dịch vụ bảo mật.
    /// </summary>
    public static class SecurityRegister
    {
        /// <summary>
        /// Đăng ký các dịch vụ bảo mật.
        /// </summary>
        /// <param name="services">Đối tượng IServiceCollection.</param>
        /// <param name="configuration">Đối tượng IConfiguration.</param>
        public static void RegisterSecurityServices(this IServiceCollection services, IConfiguration configuration)
        {
            var autConfig = configuration.GetSection("AutConfig").Get<AutConfig>();

            var jwtSettings = configuration.GetSection("JwtSettings").Get<JwtSettings>();
            var key = Encoding.UTF8.GetBytes(jwtSettings.Secret);


            services.AddIdentity<User, Role>(
                options =>
                {
                    #region Password settings
                    // Password settings
                    options.Password.RequireDigit = false;
                    options.Password.RequiredLength = 6;
                    options.Password.RequireNonAlphanumeric = false;
                    options.Password.RequireUppercase = false;
                    options.Password.RequireLowercase = false;
                    #endregion
                    options.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultEmailProvider;

                    options.Lockout.AllowedForNewUsers = true;
                    options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
                    options.Lockout.MaxFailedAccessAttempts = 5;

                    options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._";
                    options.User.RequireUniqueEmail = true;

                })
                    .AddEntityFrameworkStores<LadaDbContext>()
                    .AddErrorDescriber<VietnamIdentityErrorDescriber>()
                    .AddDefaultTokenProviders();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata = false;
                options.SaveToken = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidIssuer = jwtSettings.Issuer,
                    ValidAudience = jwtSettings.Audience
                };
            });

            // Đăng ký Authorization với Founder Bypass Handler
            services.AddAuthorization();

            services.AddScoped<IAuthorizationHandler, FounderBypassAuthorizationHandler>();

            
        }

        /// <summary>
        /// Đăng ký các middleware bảo mật.
        /// </summary>
        /// <param name="app">Đối tượng IApplicationBuilder.</param>
        public static void RegisterSecurity(this IApplicationBuilder app)
        {
            app.UseAuthentication();
            app.UseAuthorization();
        }
    }


}
