using Microsoft.AspNetCore.Http;
using System.Security.Claims;

namespace TakeoutSaaS.Application.App.Subscriptions;

internal static class SubscriptionTenantAccess
{
    private const string PermissionClaimType = "permission";
    private const string PlatformAdminRole = "PlatformAdmin";

    public static bool ShouldIgnoreTenantFilter(IHttpContextAccessor httpContextAccessor)
    {
        var httpContext = httpContextAccessor.HttpContext;
        if (httpContext == null)
        {
            // Background jobs / out-of-request execution should process across tenants.
            return true;
        }

        var user = httpContext.User;
        if (user?.Identity?.IsAuthenticated != true)
        {
            return false;
        }

        if (user.IsInRole(PlatformAdminRole))
        {
            return true;
        }

        var permissions = user.FindAll(PermissionClaimType)
            .Select(c => c.Value?.Trim())
            .Where(v => !string.IsNullOrWhiteSpace(v))
            .ToHashSet(StringComparer.OrdinalIgnoreCase);

        // Platform-level tenant permissions imply cross-tenant visibility.
        return permissions.Contains("tenant:read");
    }
}
