namespace Kit.Helpers.Auth
{
    using Kit.Helpers;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Filters;
    using Microsoft.AspNetCore.Routing;
    using Microsoft.Extensions.Configuration;

    public class SecurityKeyFilter : IAuthorizationFilter
    {
        private string _authServiceUrl;
        private ISecurityKeyService _securityKeyService;

        public SecurityKeyFilter(IConfiguration configuration, ISecurityKeyService securityKeyService)
        {
            _authServiceUrl = configuration["Auth:ServiceUrl"];
            _securityKeyService = securityKeyService;
        }


        public bool AllowMultiple { get { return false; } }


        public void OnAuthorization(AuthorizationFilterContext context)
        {

            var routeData = context.HttpContext.GetRouteData();

            //// securityKeyName
            string securityKeyName = routeData.DataTokens["APP_SecurityKeyName"] as string;
            if (string.IsNullOrWhiteSpace(securityKeyName)) return;

            //// requestSecurityKeyValue
            string requestSecurityKeyValue = context.HttpContext.Request.Headers.ReadAuthHeader();
            if (!_securityKeyService.CheckKey(securityKeyName, requestSecurityKeyValue))
            {

                string method = context.HttpContext.Request.Method.ToLower();
                string href = $"{_authServiceUrl}/noaccess/{method}";
                string hrefWithQuery = href + context.HttpContext.Request.QueryString;
                context.Result = new RedirectResult(hrefWithQuery);

                if (method.Equals("get"))
                {
                    context.Result = new RedirectResult(hrefWithQuery);
                }
                if (method.Equals("post"))
                {
                    context.Result = new JsonResult(new { State = 307, Url = hrefWithQuery });
                }
            }
        }
    }
}