using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using MTWorkHR.Core.Global;
using MTWorkHR.Identity.DBContext;
using MTWorkHR.Identity.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MTWorkHR.Identity
{
    public static class IdentityServiceRegistration
    {
        public static IServiceCollection AddIdentityServices(this IServiceCollection services, AppSettingsConfiguration config)
        {
            services.AddSingleton(config);

            var vv = config.ConnectionStrings.MTWorkHRConnectionString;
            services.AddDbContext<HRIdentityDBContext>(options =>
                options.UseSqlServer(
                    config.ConnectionStrings.MTWorkHRConnectionString  //configuration.GetSection("ConnectionString:MTWorkHRConnectionString").Value
                    ));
           
            services.AddIdentity<ApplicationUser, ApplicationRole>().AddEntityFrameworkStores<HRIdentityDBContext>().AddDefaultTokenProviders();

           
            services.AddAuthentication(options => {
                 options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; // "bearer"
                 options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

            }).AddJwtBearer(o=> o.TokenValidationParameters = new TokenValidationParameters 
                {
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.Zero,
                    ValidIssuer = config.JwtSettings.Issuer,
                    ValidAudience = config.JwtSettings.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config.JwtSettings.SecretKey))
                }) ;
            return services;
        }
    }
}