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

namespace Knot.Shared.Infrastructure.Middleware;

public class AdminAuthMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task InvokeAsync(HttpContext context, IConfiguration configuration)
    {
        if (context.Request.Path.StartsWithSegments("/api/admin"))
        {
            var expectedUser = configuration["KNOT_ADMIN_USER"];
            var expectedPass = configuration["KNOT_ADMIN_PASSWORD"];

            if (string.IsNullOrEmpty(expectedUser) || string.IsNullOrEmpty(expectedPass))
            {
                context.Response.StatusCode = 500;
                await context.Response.WriteAsync("Admin credentials not configured on server.");
                return;
            }

            if (!context.Request.Headers.ContainsKey("Authorization"))
            {
                context.Response.Headers.Append("WWW-Authenticate", "Basic realm=\"Admin Area\"");
                context.Response.StatusCode = 401;
                return;
            }

            try
            {
                var authHeader = AuthenticationHeaderValue.Parse(context.Request.Headers["Authorization"]);
                var credentialBytes = Convert.FromBase64String(authHeader.Parameter ?? string.Empty);
                var credentials = Encoding.UTF8.GetString(credentialBytes).Split(':', 2);

                var username = credentials[0];
                var password = credentials[1];

                if (username != expectedUser || password != expectedPass)
                {
                    context.Response.StatusCode = 403;
                    return;
                }
            }
            catch
            {
                context.Response.StatusCode = 401;
                return;
            }
        }

        await _next(context);
    }
}
