using VentaUniformes.Application.Interfaces.External;
using VentaUniformes.External.GetTokenJWT;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VentaUniformes.Domain.Enums;
using Microsoft.VisualBasic.FileIO;
using VentaUniformes.External.ValidateTokenJwt;

namespace VentaUniformes.External
{
    public static class DependencyInjectionService
    {
        public static IServiceCollection AddExternal(this IServiceCollection services, IConfiguration config)
        {

            services.AddSingleton<IGetTokenJwtService, GetTokenJwtService>();
            services.AddSingleton<IValidateTokenService, ValidateTokenJwtService>();
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(option =>
            {
                option.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["SecretKeyJwt"])),
                    ValidIssuer = config["IssuerJWT"],
                    ValidAudience = config["AudienceJwt"]

                };
                option.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var cookie = context.Request.Cookies["JwtToken"];
                        if (!string.IsNullOrEmpty(cookie))
                        {
                            context.Token = cookie;
                        }
                        return Task.CompletedTask;
                    }
                };
            }
             );
            services.AddAuthorization(options =>
            {
                options.AddPolicy("AdminOnly", policy => policy.RequireRole(RoleUserType.Admin.ToString()));
            });

            //services.AddAuthorization();
            return services;
        }
    }
}
