using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System.Net;
using System.Net.Http.Headers;
using System.Text;

namespace Lada.Framework.Hangfires
{
    public class HangfireBasicAuthMiddleware
    {
        private readonly RequestDelegate next;
        private readonly IConfiguration _config;
        public HangfireBasicAuthMiddleware(RequestDelegate next, IConfiguration configuration)
        {
            this.next = next;
            _config = configuration;
        }
        public async Task InvokeAsync(HttpContext context)
        {
            if (context.Request.Path.StartsWithSegments("/hangfire"))
            {
                string authHeader = context.Request.Headers["Authorization"];
                if (authHeader != null && authHeader.StartsWith("Basic "))
                {
                    // Get the credentials from request header
                    var header = AuthenticationHeaderValue.Parse(authHeader);
                    var inBytes = Convert.FromBase64String(header.Parameter);
                    var credentials = Encoding.UTF8.GetString(inBytes).Split(':');
                    var username = credentials[0];
                    var password = credentials[1];
                    var validUserName = _config.GetSection("Hangfire:UserName").Value;
                    var validPassword = _config.GetSection("Hangfire:Password").Value;
                    // validate credentials
                    if (username.Equals(validUserName)
                      && password.Equals(validPassword))
                    {
                        await next.Invoke(context).ConfigureAwait(false);
                        return;
                    }
                }
                context.Response.Headers["WWW-Authenticate"] = "Basic";
                context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            }
            else
            {
                await next.Invoke(context).ConfigureAwait(false);
            }
        }
    }
}
