using System.Net;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.MxGateway.Server.Configuration;

namespace ZB.MOM.WW.MxGateway.Server.Dashboard;

/// <summary>
/// Authorizes a dashboard request by checking either: (a) the LDAP-issued
/// role claim satisfies <see cref="DashboardAuthorizationRequirement.RequiredRoles"/>,
/// (b) authentication is fully disabled, or (c) the request is from loopback
/// and <c>MxGateway:Dashboard:AllowAnonymousLocalhost</c> is on.
/// </summary>
public sealed class DashboardAuthorizationHandler(
    IHttpContextAccessor httpContextAccessor,
    IOptions<GatewayOptions> options) : AuthorizationHandler<DashboardAuthorizationRequirement>
{
    /// <inheritdoc />
    protected override Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        DashboardAuthorizationRequirement requirement)
    {
        GatewayOptions gatewayOptions = options.Value;

        if (gatewayOptions.Authentication.Mode == AuthenticationMode.Disabled)
        {
            context.Succeed(requirement);

            return Task.CompletedTask;
        }

        if (gatewayOptions.Dashboard.AllowAnonymousLocalhost && IsLoopbackRequest())
        {
            context.Succeed(requirement);

            return Task.CompletedTask;
        }

        if (context.User.Identity?.IsAuthenticated != true)
        {
            return Task.CompletedTask;
        }

        foreach (string role in requirement.RequiredRoles)
        {
            if (context.User.IsInRole(role))
            {
                context.Succeed(requirement);
                return Task.CompletedTask;
            }
        }

        return Task.CompletedTask;
    }

    private bool IsLoopbackRequest()
    {
        IPAddress? remoteAddress = httpContextAccessor.HttpContext?.Connection.RemoteIpAddress;

        return remoteAddress is not null && IPAddress.IsLoopback(remoteAddress);
    }
}
