using Hangfire;
using Hangfire.Dashboard;

namespace Nalu.Web.Infrastructure;

/// <summary>
/// Allows Hangfire Dashboard access only from localhost or users in the Admin role.
/// </summary>
public sealed class HangfireDashboardAuth : IDashboardAuthorizationFilter
{
    public bool Authorize(DashboardContext context)
    {
        var http = context.GetHttpContext();

        // Always allow localhost (dev / ops access)
        if (http.Connection.RemoteIpAddress is { } ip &&
            (System.Net.IPAddress.IsLoopback(ip) ||
             ip.Equals(http.Connection.LocalIpAddress)))
        {
            return true;
        }

        // Allow authenticated Admin users in production
        return http.User.Identity?.IsAuthenticated == true
            && http.User.IsInRole("Admin");
    }
}
