using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Net.Mime;
using System.Threading.Tasks;

namespace HRD.LDAPService.JWT
{
    public class JwtMiddleware
    {
        private readonly RequestDelegate _next;

        public JwtMiddleware(RequestDelegate next)
        {
            _next = next;
        }

#pragma warning disable AMNF0001 // Asynchronous method name is not ending with 'Async'

        public async Task Invoke(HttpContext httpContext)
#pragma warning restore AMNF0001 // Asynchronous method name is not ending with 'Async'
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException($"Jwt {httpContext} is null");
            }

            if (JwtTokenConfig.AktivateAuthorizationFilter)
            {
                var path = httpContext.Request.Path.Value;
                if (!string.IsNullOrEmpty(path))
                {
                    if (JwtTokenConfig.IsInBlackList(path))
                    {
                        httpContext.Response.ContentType = MediaTypeNames.Application.Json;
                        httpContext.Response.StatusCode = StatusCodes.Status403Forbidden;
                        var responseJson = JsonConvert.SerializeObject($"Path is in a blacklist: '${path}'");
                        await httpContext.Response.WriteAsync(responseJson).ConfigureAwait(false);
                        return;
                    }

                    if (JwtTokenConfig.IsInWhiteList(path))
                    {
                        await _next(httpContext).ConfigureAwait(false); // calling next middleware
                        return;
                    }
                }
            }
            var headerAuthorization = httpContext.Request.Headers["Authorization"];

            var authorizationType = headerAuthorization.FirstOrDefault()?.Split(" ").First();
            if (authorizationType == null)
            {
                await _next(httpContext).ConfigureAwait(false); // calling next middleware
                return;
            }
            var jwt = headerAuthorization.FirstOrDefault();

            //Check token
            if (JwtManager.IsValidatJwtTokenSubject(jwt))
            {
                var user = JwtManager.DecryptTokenAsLdapUser(jwt);
                if (user == default)
                {
                    httpContext.Response.ContentType = MediaTypeNames.Application.Json;
                    httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
                    var responseJson = JsonConvert.SerializeObject($"Failed to decode JWT. The User was not valid");
                    await httpContext.Response.WriteAsync(responseJson).ConfigureAwait(false);
                    return;
                }

                httpContext.Items[JwtGlobals.HttpContextItem_IsValidHenselToken] = "true";
                httpContext.Items[JwtGlobals.HttpContextItem_LdapUser] = user;
                await _next(httpContext).ConfigureAwait(false); // calling next middleware
                return;
            }
            else
            {
                httpContext.Response.ContentType = MediaTypeNames.Application.Json;
                httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
                var responseJson = JsonConvert.SerializeObject($"The JWT was not valid.");
                await httpContext.Response.WriteAsync(responseJson).ConfigureAwait(false);
                return;
            }
        }

        private string GetAction(HttpContext httpContext)
        {
            if (httpContext.Request.Headers.ContainsKey("action"))
            {
                return httpContext.Request.Headers["action"].ToString();
            }
            return string.Empty;
        }
    }
}