using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
using System.Security.Claims;
using System.Text.Encodings.Web;

namespace ApiTerceiroSimulador.Code
{
    public class MyAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
    {
        private const string API_KEY = "123";

        public MyAuthenticationHandler(
            IOptionsMonitor<AuthenticationSchemeOptions> options,
            ILoggerFactory logger,
            UrlEncoder encoder)
        : base(options, logger, encoder)
        {
            // inject services here
        }

        //protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
        //{
        // Read token from HTTP request header
        //string authorizationHeader = Request.Headers["Authorization"]!;
        //if (string.IsNullOrEmpty(authorizationHeader) || !authorizationHeader.StartsWith("Bearer "))
        //{
        //    return AuthenticateResult.Fail("no token");
        //}
        //// Remove "Bearer" to get pure token data
        //var token = authorizationHeader.Substring("Bearer ".Length);

        //    try
        //    {
        //        //auth logic
        //        if (token != "123")
        //            throw new Exception("Token inválido!");

        //        var claims = new[] { new Claim(ClaimTypes.Name, "Test") };
        //        var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Tokens"));
        //        var ticket = new AuthenticationTicket(principal, this.Scheme.Name);

        //        await Task.Delay(1);

        //        return AuthenticateResult.Success(ticket);
        //    }
        //    catch (Exception ex)
        //    {
        //        //oops
        //        return AuthenticateResult.Fail(ex);
        //    }
        //}

        protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            string apikey = Request.Headers["XApiKey"]!;
            if (string.IsNullOrEmpty(apikey))
                return AuthenticateResult.Fail("Api Key was not provided");

            try
            {
                //auth logic
                if (apikey != API_KEY)
                    return AuthenticateResult.Fail("Unauthorized client!");

                var claims = new[] { new Claim(ClaimTypes.Name, "Test") };
                var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Tokens"));
                var ticket = new AuthenticationTicket(principal, this.Scheme.Name);

                await Task.Delay(1);

                return AuthenticateResult.Success(ticket);
            }
            catch (Exception ex)
            {
                //oops
                return AuthenticateResult.Fail(ex);
            }
        }
    }
}
