<?php

namespace App\Filament\Resources;

use App\Filament\Pages\CrossEnvironmentComparePage;
use App\Filament\Resources\ManagedEnvironmentResource\Pages;
use App\Filament\Resources\ManagedEnvironmentResource\RelationManagers;
use App\Http\Controllers\RbacDelegatedAuthController;
use App\Jobs\BulkTenantSyncJob;
use App\Jobs\SyncPoliciesJob;
use App\Models\EntraGroup;
use App\Models\EntraRoleDefinition;
use App\Models\ProviderConnection;
use App\Models\ManagedEnvironment;
use App\Models\ManagedEnvironmentOnboardingSession;
use App\Models\ManagedEnvironmentTriageReview;
use App\Models\User;
use App\Models\Workspace;
use App\Services\Audit\WorkspaceAuditLogger;
use App\Services\Auth\CapabilityResolver;
use App\Services\Auth\WorkspaceCapabilityResolver;
use App\Services\Directory\EntraGroupLabelResolver;
use App\Services\Directory\RoleDefinitionsSyncService;
use App\Services\Graph\GraphClientInterface;
use App\Services\Intune\AuditLogger;
use App\Services\Intune\RbacOnboardingService;
use App\Services\OperationRunService;
use App\Services\Operations\BulkSelectionIdentity;
use App\Services\PortfolioTriage\ManagedEnvironmentTriageReviewService;
use App\Services\Providers\AdminConsentUrlFactory;
use App\Services\Tenants\TenantActionPolicySurface;
use App\Services\Tenants\TenantOperabilityService;
use App\Services\Verification\StartVerification;
use App\Services\Workspaces\WorkspaceLifecycleService;
use App\Support\Audit\AuditActionId;
use App\Support\Auth\Capabilities;
use App\Support\Auth\UiTooltips;
use App\Support\BackupHealth\TenantBackupHealthAssessment;
use App\Support\BackupHealth\TenantBackupHealthResolver;
use App\Support\Badges\BadgeDomain;
use App\Support\Badges\BadgeRenderer;
use App\Support\Badges\TagBadgeDomain;
use App\Support\Badges\TagBadgeRenderer;
use App\Support\Filament\TablePaginationProfiles;
use App\Support\ManagedEnvironmentLinks;
use App\Support\OperationRunLinks;
use App\Support\OpsUx\OperationUxPresenter;
use App\Support\OpsUx\ProviderOperationStartResultPresenter;
use App\Support\OpsUx\OpsUxBrowserEvents;
use App\Support\Navigation\CanonicalNavigationContext;
use App\Support\PortfolioTriage\PortfolioArrivalContextToken;
use App\Support\PortfolioTriage\ManagedEnvironmentTriageReviewStateResolver;
use App\Support\Rbac\UiEnforcement;
use App\Support\Navigation\RelatedContextEntry;
use App\Support\Navigation\UnavailableRelationState;
use App\Support\RestoreSafety\RestoreSafetyResolver;
use App\Support\Tenants\TenantActionDescriptor;
use App\Support\Tenants\TenantActionSurface;
use App\Support\Tenants\TenantInteractionLane;
use App\Support\Tenants\TenantLifecyclePresentation;
use App\Support\Tenants\TenantOperabilityOutcome;
use App\Support\Tenants\TenantOperabilityQuestion;
use App\Support\Tenants\TenantRecoveryTriagePresentation;
use App\Support\Providers\TargetScope\ProviderConnectionSurfaceSummary;
use App\Support\Ui\ActionSurface\ActionSurfaceDeclaration;
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceInspectAffordance;
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceProfile;
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceSlot;
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceType;
use App\Support\Ui\GovernanceActions\GovernanceActionCatalog;
use App\Support\Workspaces\WorkspaceContext;
use BackedEnum;
use Filament\Actions;
use Filament\Actions\ActionGroup;
use Filament\Actions\BulkActionGroup;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Infolists;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Contracts\HasTable;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\HtmlString;
use Illuminate\Support\Str;
use UnitEnum;

class ManagedEnvironmentResource extends Resource
{
    // ... [Properties Omitted for Brevity] ...
    protected static ?string $model = ManagedEnvironment::class;

    protected static bool $isDiscovered = false;

    protected static bool $isScopedToTenant = false;

    protected static bool $isGloballySearchable = false;

    protected static ?string $recordTitleAttribute = 'name';

    protected static ?string $recordRouteKeyName = 'slug';

    protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-building-office-2';

    protected static string|UnitEnum|null $navigationGroup = 'Settings';

    /**
     * @var array<string, Collection<int, TenantActionDescriptor>>
     */
    protected static array $tenantActionCatalogCache = [];

    private const string POSTURE_SNAPSHOT_REQUEST_KEY = 'tenant_resource.posture_snapshot';

    private const string TRIAGE_REVIEW_SNAPSHOT_REQUEST_KEY = 'managed_environment_resource.triage_review_snapshot';

    /**
     * @var array<string, true>
     */
    private const array TRIAGE_SORT_VALUES = [
        TenantRecoveryTriagePresentation::TRIAGE_SORT_DEFAULT => true,
        TenantRecoveryTriagePresentation::TRIAGE_SORT_WORST_FIRST => true,
    ];

    /**
     * ManagedEnvironment creation is handled exclusively by the onboarding wizard.
     * The CRUD create page has been removed.
     */
    public static function canCreate(): bool
    {
        return false;
    }

    public static function canEdit(Model $record): bool
    {
        $user = auth()->user();

        if (! $user instanceof User) {
            return false;
        }

        /** @var CapabilityResolver $resolver */
        $resolver = app(CapabilityResolver::class);

        return $record instanceof ManagedEnvironment
            && ! $record->isRemovedFromWorkspace()
            && ! $record->workspace?->isClosed()
            && $resolver->can($user, $record, Capabilities::TENANT_MANAGE);
    }

    public static function canDelete(Model $record): bool
    {
        $user = auth()->user();

        if (! $user instanceof User) {
            return false;
        }

        /** @var CapabilityResolver $resolver */
        $resolver = app(CapabilityResolver::class);

        return $record instanceof ManagedEnvironment
            && ! $record->isRemovedFromWorkspace()
            && ! $record->workspace?->isClosed()
            && $resolver->can($user, $record, Capabilities::TENANT_DELETE);
    }

    public static function canDeleteAny(): bool
    {
        $user = auth()->user();

        if (! $user instanceof User) {
            return false;
        }

        return static::userCanDeleteAnyTenant($user);
    }

    public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
    {
        return ActionSurfaceDeclaration::forResource(ActionSurfaceProfile::CrudListAndView, ActionSurfaceType::CrudListFirstResource)
            ->withListRowPrimaryActionLimit(1)
            ->satisfy(ActionSurfaceSlot::ListHeader, 'List page provides a capability-gated create action.')
            ->satisfy(ActionSurfaceSlot::InspectAffordance, ActionSurfaceInspectAffordance::ClickableRow->value)
            ->satisfy(ActionSurfaceSlot::ListRowMoreMenu, 'At most one non-inspect row action stays primary; overflow keeps helpers first, workflow actions next, and destructive actions last.')
            ->satisfy(ActionSurfaceSlot::ListBulkMoreGroup, 'Bulk actions are grouped under "More".')
            ->satisfy(ActionSurfaceSlot::ListEmptyState, 'Create action is reused in the list empty state.')
            ->satisfy(ActionSurfaceSlot::DetailHeader, 'ManagedEnvironment view remains the workflow-heavy special type: shared administrative actions stay grouped into external-link, setup, triage, and lifecycle buckets, while navigation-only context stays outside the header action strip.');
    }

    public static function makeAdminConsentAction(): Actions\Action
    {
        return UiEnforcement::forAction(
            Actions\Action::make('admin_consent')
                ->label('Grant admin consent')
                ->icon('heroicon-o-clipboard-document')
                ->url(fn (ManagedEnvironment $record): string => static::adminConsentUrl($record) ?? '#')
                ->visible(fn (ManagedEnvironment $record): bool => static::adminConsentUrl($record) !== null
                    && ! $record->isRemovedFromWorkspace()
                    && ! $record->workspace?->isClosed())
                ->openUrlInNewTab(),
        )
            ->preserveVisibility()
            ->requireCapability(Capabilities::TENANT_MANAGE)
            ->apply();
    }

    public static function makeOpenInEntraAction(): Actions\Action
    {
        return Actions\Action::make('open_in_entra')
            ->label('Open in Entra')
            ->icon('heroicon-o-arrow-top-right-on-square')
            ->url(fn (ManagedEnvironment $record): string => static::entraUrl($record) ?? '#')
            ->visible(fn (ManagedEnvironment $record): bool => static::entraUrl($record) !== null)
            ->openUrlInNewTab();
    }

    public static function makeMembershipsAction(): Actions\Action
    {
        return UiEnforcement::forAction(
            Actions\Action::make('memberships')
                ->label('Manage access scope')
                ->icon('heroicon-o-users')
                ->url(fn (ManagedEnvironment $record): string => ManagedEnvironmentLinks::accessScopesUrl($record)),
        )
            ->requireCapability(Capabilities::TENANT_MEMBERSHIP_VIEW)
            ->tooltip('You do not have permission to view environment access scopes.')
            ->preserveVisibility()
            ->apply();
    }

    public static function makeSyncTenantAction(): Actions\Action
    {
        return UiEnforcement::forAction(
            Actions\Action::make('syncTenant')
                ->label('Sync')
                ->icon('heroicon-o-arrow-path')
                ->color('warning')
                ->requiresConfirmation()
                ->visible(fn (ManagedEnvironment $record): bool => static::syncActionVisible($record))
                ->action(function (ManagedEnvironment $record, AuditLogger $auditLogger, $livewire = null): void {
                    static::handleSyncTenantAction($record, $auditLogger, $livewire);
                })
        )
            ->preserveVisibility()
            ->requireCapability(Capabilities::TENANT_SYNC)
            ->apply();
    }

    public static function makeVerifyConfigurationAction(string $surfaceKind = 'tenant_list_row'): Actions\Action
    {
        return UiEnforcement::forAction(
            Actions\Action::make('verify')
                ->label('Verify configuration')
                ->icon('heroicon-o-check-badge')
                ->color('primary')
                ->requiresConfirmation()
                ->visible(fn (ManagedEnvironment $record): bool => static::verificationActionVisible($record))
                ->action(function (ManagedEnvironment $record, StartVerification $verification, $livewire = null) use ($surfaceKind): void {
                    static::handleVerifyConfigurationAction($record, $verification, $livewire, $surfaceKind);
                }),
        )
            ->preserveVisibility()
            ->requireCapability(Capabilities::PROVIDER_RUN)
            ->apply();
    }

    /**
     * @return array<string, mixed>
     */
    public static function tenantViewTriageState(): array
    {
        return static::portfolioReturnFiltersFromRequest(request()->query());
    }

    public static function tenantViewTriageGroupVisible(ManagedEnvironment $tenant): bool
    {
        return static::selectedActionTriageReviewRowForTenant($tenant, static::tenantViewTriageState()) !== null
            && static::userCanSeeTriageReviewAction($tenant);
    }

    public static function makeTenantViewMarkReviewedAction(): Actions\Action
    {
        return Actions\Action::make('markReviewed')
            ->label('Mark reviewed')
            ->icon('heroicon-o-check-circle')
            ->color('success')
            ->requiresConfirmation()
            ->modalHeading('Mark reviewed')
            ->modalDescription(fn (ManagedEnvironment $record): string => static::triageReviewActionModalDescription(
                $record,
                static::tenantViewTriageState(),
                ManagedEnvironmentTriageReview::STATE_REVIEWED,
            ))
            ->visible(fn (ManagedEnvironment $record): bool => static::selectedActionTriageReviewRowForTenant(
                $record,
                static::tenantViewTriageState(),
            ) !== null && static::userCanSeeTriageReviewAction($record))
            ->disabled(fn (ManagedEnvironment $record): bool => static::triageReviewActionIsDisabled($record))
            ->tooltip(fn (ManagedEnvironment $record): ?string => static::triageReviewActionTooltip($record))
            ->before(function (ManagedEnvironment $record): void {
                static::authorizeTriageReviewAction($record);
            })
            ->action(function (ManagedEnvironment $record, ManagedEnvironmentTriageReviewService $service): void {
                static::handleTriageReviewMutation(
                    tenant: $record,
                    triageState: static::tenantViewTriageState(),
                    targetManualState: ManagedEnvironmentTriageReview::STATE_REVIEWED,
                    service: $service,
                );
            });
    }

    public static function makeTenantViewMarkFollowUpNeededAction(): Actions\Action
    {
        return Actions\Action::make('markFollowUpNeeded')
            ->label('Mark follow-up needed')
            ->icon('heroicon-o-exclamation-circle')
            ->color('warning')
            ->requiresConfirmation()
            ->modalHeading('Mark follow-up needed')
            ->modalDescription(fn (ManagedEnvironment $record): string => static::triageReviewActionModalDescription(
                $record,
                static::tenantViewTriageState(),
                ManagedEnvironmentTriageReview::STATE_FOLLOW_UP_NEEDED,
            ))
            ->visible(fn (ManagedEnvironment $record): bool => static::selectedActionTriageReviewRowForTenant(
                $record,
                static::tenantViewTriageState(),
            ) !== null && static::userCanSeeTriageReviewAction($record))
            ->disabled(fn (ManagedEnvironment $record): bool => static::triageReviewActionIsDisabled($record))
            ->tooltip(fn (ManagedEnvironment $record): ?string => static::triageReviewActionTooltip($record))
            ->before(function (ManagedEnvironment $record): void {
                static::authorizeTriageReviewAction($record);
            })
            ->action(function (ManagedEnvironment $record, ManagedEnvironmentTriageReviewService $service): void {
                static::handleTriageReviewMutation(
                    tenant: $record,
                    triageState: static::tenantViewTriageState(),
                    targetManualState: ManagedEnvironmentTriageReview::STATE_FOLLOW_UP_NEEDED,
                    service: $service,
                );
            });
    }

    public static function makeRestoreTenantAction(TenantActionSurface $surface, ?string $permissionTooltip = null): Actions\Action
    {
        $builder = UiEnforcement::forAction(
            Actions\Action::make('restore')
                ->label(fn (): string => GovernanceActionCatalog::rule('restore_tenant')->canonicalLabel)
                ->color('success')
                ->icon(fn (ManagedEnvironment $record): string => static::lifecycleActionDescriptor($record, $surface)?->icon ?? 'heroicon-o-arrow-uturn-left')
                ->successNotificationTitle(fn (): string => GovernanceActionCatalog::rule('restore_tenant')->successTitle)
                ->requiresConfirmation()
                ->modalHeading(GovernanceActionCatalog::rule('restore_tenant')->modalHeading)
                ->modalDescription(GovernanceActionCatalog::rule('restore_tenant')->modalDescription)
                ->visible(fn (ManagedEnvironment $record): bool => static::lifecycleActionDescriptor($record, $surface)?->key === 'restore')
                ->action(function (ManagedEnvironment $record, WorkspaceAuditLogger $auditLogger): void {
                    static::restoreTenant($record, $auditLogger);
                })
        )
            ->preserveVisibility()
            ->requireCapability(Capabilities::TENANT_DELETE);

        if ($permissionTooltip !== null && $permissionTooltip !== '') {
            $builder->tooltip($permissionTooltip);
        }

        return $builder->apply();
    }

    public static function makeArchiveTenantAction(TenantActionSurface $surface, ?string $permissionTooltip = null): Actions\Action
    {
        $builder = UiEnforcement::forAction(
            Actions\Action::make('archive')
                ->label(fn (): string => GovernanceActionCatalog::rule('archive_tenant')->canonicalLabel)
                ->color('danger')
                ->icon(fn (ManagedEnvironment $record): string => static::lifecycleActionDescriptor($record, $surface)?->icon ?? 'heroicon-o-archive-box-x-mark')
                ->successNotificationTitle(fn (): string => GovernanceActionCatalog::rule('archive_tenant')->successTitle)
                ->requiresConfirmation()
                ->modalHeading(GovernanceActionCatalog::rule('archive_tenant')->modalHeading)
                ->modalDescription(GovernanceActionCatalog::rule('archive_tenant')->modalDescription)
                ->form([
                    Forms\Components\Textarea::make('archive_reason')
                        ->label('Archive reason')
                        ->rows(4)
                        ->required()
                        ->maxLength(2000),
                ])
                ->visible(fn (ManagedEnvironment $record): bool => static::lifecycleActionDescriptor($record, $surface)?->key === 'archive')
                ->action(function (ManagedEnvironment $record, array $data, WorkspaceAuditLogger $auditLogger): void {
                    static::archiveTenant($record, $auditLogger, (string) ($data['archive_reason'] ?? ''));
                })
        )
            ->preserveVisibility()
            ->requireCapability(Capabilities::TENANT_DELETE);

        if ($permissionTooltip !== null && $permissionTooltip !== '') {
            $builder->tooltip($permissionTooltip);
        }

        return $builder->apply();
    }

    public static function makeRemoveTenantFromWorkspaceAction(?string $permissionTooltip = null): Actions\Action
    {
        $builder = UiEnforcement::forAction(
            Actions\Action::make('remove_from_workspace')
                ->label('Remove environment')
                ->color('danger')
                ->icon('heroicon-o-no-symbol')
                ->requiresConfirmation()
                ->modalHeading('Remove environment from workspace')
                ->modalDescription('The tenant remains available for audit, operation history, evidence, and administrative inspection, but it is no longer selectable as active tenant context.')
                ->form([
                    Forms\Components\Textarea::make('removal_reason')
                        ->label('Removal reason')
                        ->rows(4)
                        ->required()
                        ->minLength(5)
                        ->maxLength(2000),
                ])
                ->visible(fn (ManagedEnvironment $record): bool => static::tenantWorkspaceRemovalActionVisible($record))
                ->disabled(fn (ManagedEnvironment $record): bool => (bool) $record->workspace?->isClosed())
                ->tooltip(fn (ManagedEnvironment $record): ?string => $record->workspace?->isClosed()
                    ? 'Closed workspaces are read-only. Reopen the workspace before removing tenants.'
                    : null)
                ->action(function (ManagedEnvironment $record, array $data, WorkspaceLifecycleService $service): void {
                    $user = auth()->user();

                    if (! $user instanceof User) {
                        abort(403);
                    }

                    if (! $user->canAccessTenant($record)) {
                        abort(404);
                    }

                    $service->removeTenantFromWorkspace($record, $user, (string) ($data['removal_reason'] ?? ''));

                    Notification::make()
                        ->title('Tenant removed from workspace')
                        ->body('The tenant remains available for administrative inspection and historical evidence, but it is no longer selectable as active context.')
                        ->success()
                        ->send();
                })
        )
            ->preserveVisibility()
            ->requireCapability(Capabilities::TENANT_DELETE);

        if ($permissionTooltip !== null && $permissionTooltip !== '') {
            $builder->tooltip($permissionTooltip);
        }

        return $builder->apply();
    }

    public static function makeRestoreTenantToWorkspaceAction(?string $permissionTooltip = null): Actions\Action
    {
        $builder = UiEnforcement::forAction(
            Actions\Action::make('restore_to_workspace')
                ->label('Restore environment')
                ->color('success')
                ->icon('heroicon-o-arrow-uturn-left')
                ->requiresConfirmation()
                ->modalHeading('Restore environment to workspace')
                ->modalDescription('Restoring the tenant makes it eligible for normal workspace tenant selection and new tenant operations again, subject to its lifecycle and RBAC.')
                ->form([
                    Forms\Components\Textarea::make('restore_reason')
                        ->label('Restore reason')
                        ->rows(4)
                        ->required()
                        ->minLength(5)
                        ->maxLength(2000),
                ])
                ->visible(fn (ManagedEnvironment $record): bool => static::tenantWorkspaceRestoreActionVisible($record))
                ->disabled(fn (ManagedEnvironment $record): bool => (bool) $record->workspace?->isClosed())
                ->tooltip(fn (ManagedEnvironment $record): ?string => $record->workspace?->isClosed()
                    ? 'Closed workspaces are read-only. Reopen the workspace before restoring tenants.'
                    : null)
                ->action(function (ManagedEnvironment $record, array $data, WorkspaceLifecycleService $service): void {
                    $user = auth()->user();

                    if (! $user instanceof User) {
                        abort(403);
                    }

                    if (! $user->canAccessTenant($record)) {
                        abort(404);
                    }

                    $service->restoreTenantToWorkspace($record, $user, (string) ($data['restore_reason'] ?? ''));

                    Notification::make()
                        ->title('Tenant restored to workspace')
                        ->body('The tenant can be selected again when its lifecycle and RBAC allow it.')
                        ->success()
                        ->send();
                })
        )
            ->preserveVisibility()
            ->requireCapability(Capabilities::TENANT_DELETE);

        if ($permissionTooltip !== null && $permissionTooltip !== '') {
            $builder->tooltip($permissionTooltip);
        }

        return $builder->apply();
    }

    private static function syncActionVisible(ManagedEnvironment $record): bool
    {
        if (! static::tenantSetupMutationVisible($record)) {
            return false;
        }

        $user = auth()->user();

        if (! $user instanceof User) {
            return false;
        }

        return $user->canAccessTenant($record);
    }

    private static function handleSyncTenantAction(ManagedEnvironment $record, AuditLogger $auditLogger, mixed $livewire = null): void
    {
        $user = auth()->user();

        if (! $user instanceof User) {
            abort(403);
        }

        if (! $user->canAccessTenant($record)) {
            abort(404);
        }

        /** @var CapabilityResolver $resolver */
        $resolver = app(CapabilityResolver::class);

        if (! $resolver->can($user, $record, Capabilities::TENANT_SYNC)) {
            abort(403);
        }

        /** @var OperationRunService $opService */
        $opService = app(OperationRunService::class);

        $supportedTypes = config('tenantpilot.supported_policy_types', []);
        $typeNames = array_map(
            static fn (array $typeConfig): string => (string) $typeConfig['type'],
            $supportedTypes,
        );
        sort($typeNames);

        $inputs = [
            'scope' => 'full',
            'types' => $typeNames,
        ];

        $opRun = $opService->ensureRun(
            tenant: $record,
            type: 'policy.sync',
            inputs: $inputs,
            initiator: $user,
        );

        if (! $opRun->wasRecentlyCreated && $opService->isStaleQueuedRun($opRun)) {
            $opService->failStaleQueuedRun(
                $opRun,
                message: 'Run was queued but never started (likely a previous dispatch error). Re-queuing.'
            );

            $opRun = $opService->ensureRun(
                tenant: $record,
                type: 'policy.sync',
                inputs: $inputs,
                initiator: $user,
            );
        }

        if (! $opRun->wasRecentlyCreated && in_array($opRun->status, ['queued', 'running'], true)) {
            OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
            OperationUxPresenter::alreadyQueuedToast((string) $opRun->type)
                ->actions([
                    Actions\Action::make('view_run')
                        ->label('Open operation')
                        ->url(OperationRunLinks::view($opRun, $record)),
                ])
                ->send();

            return;
        }

        $opService->dispatchOrFail($opRun, function () use ($record, $supportedTypes, $opRun): void {
            SyncPoliciesJob::dispatch((int) $record->getKey(), $supportedTypes, null, $opRun);
        });

        $auditLogger->log(
            tenant: $record,
            action: 'tenant.sync_dispatched',
            resourceType: 'tenant',
            resourceId: (string) $record->id,
            status: 'success',
            context: ['metadata' => ['managed_environment_id' => $record->managed_environment_id]],
        );

        OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
        OperationUxPresenter::queuedToast((string) $opRun->type)
            ->actions([
                Actions\Action::make('view_run')
                    ->label('Open operation')
                    ->url(OperationRunLinks::view($opRun, $record)),
            ])
            ->send();
    }

    private static function handleVerifyConfigurationAction(
        ManagedEnvironment $record,
        StartVerification $verification,
        mixed $livewire = null,
        string $surfaceKind = 'tenant_list_row',
    ): void {
        $user = auth()->user();

        if (! $user instanceof User) {
            abort(403);
        }

        if (! $user->canAccessTenant($record)) {
            abort(404);
        }

        $result = $verification->providerConnectionCheckForTenant(
            tenant: $record,
            initiator: $user,
            extraContext: [
                'surface' => [
                    'kind' => $surfaceKind,
                ],
            ],
        );

        $runUrl = OperationRunLinks::tenantlessView($result->run);
        $notification = app(ProviderOperationStartResultPresenter::class)->notification(
            result: $result,
            blockedTitle: 'Verification blocked',
            runUrl: $runUrl,
        );

        if ($result->status === 'scope_busy') {
            OpsUxBrowserEvents::dispatchRunEnqueued($livewire);

            $notification->send();

            return;
        }

        if ($result->status === 'deduped') {
            OpsUxBrowserEvents::dispatchRunEnqueued($livewire);

            $notification->send();

            return;
        }

        if ($result->status === 'blocked') {
            $notification->send();

            return;
        }

        OpsUxBrowserEvents::dispatchRunEnqueued($livewire);

        $notification->send();
    }

    private static function userCanManageAnyTenant(User $user): bool
    {
        return static::userHasCurrentWorkspaceCapability($user, Capabilities::TENANT_MANAGE);
    }

    private static function userCanDeleteAnyTenant(User $user): bool
    {
        return static::userHasCurrentWorkspaceCapability($user, Capabilities::TENANT_DELETE);
    }

    private static function userHasCurrentWorkspaceCapability(User $user, string $capability): bool
    {
        $workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());

        if (! is_int($workspaceId)) {
            return false;
        }

        $workspace = Workspace::query()->whereKey($workspaceId)->first();

        if (! $workspace instanceof Workspace) {
            return false;
        }

        return app(WorkspaceCapabilityResolver::class)->can($user, $workspace, $capability);
    }

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->schema([
                Forms\Components\Placeholder::make('related_context')
                    ->label('Related context')
                    ->content(fn (?ManagedEnvironment $record): HtmlString => static::tenantEditContextHtml($record))
                    ->visible(fn (?ManagedEnvironment $record): bool => $record instanceof ManagedEnvironment && static::tenantEditContextEntries($record) !== []),
                Forms\Components\TextInput::make('name')
                    ->required()
                    ->maxLength(255),
                Forms\Components\Select::make('environment')
                    ->options([
                        'prod' => 'PROD',
                        'dev' => 'DEV',
                        'staging' => 'STAGING',
                        'other' => 'Other',
                    ])
                    ->default('other')
                    ->required(),
                Forms\Components\TextInput::make('managed_environment_id')
                    ->label('ManagedEnvironment ID (GUID)')
                    ->required()
                    ->maxLength(255)
                    ->unique(ignoreRecord: true),
                Forms\Components\TextInput::make('domain')
                    ->label('Primary domain')
                    ->maxLength(255)
                    ->helperText('Credentials are managed in Provider connections.'),
            ]);
    }

    public static function getEloquentQuery(): Builder
    {
        // ... [Query Omitted - No Change] ...
        $user = auth()->user();

        if (! $user instanceof User) {
            return parent::getEloquentQuery()->whereRaw('1 = 0');
        }

        $workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());

        if ($workspaceId === null) {
            return parent::getEloquentQuery()->whereRaw('1 = 0');
        }

        $tenantIds = $user->accessibleManagedEnvironmentsQuery($workspaceId)
            ->withTrashed()
            ->pluck('managed_environments.id');

        return parent::getEloquentQuery()
            ->withTrashed()
            ->whereIn('id', $tenantIds)
            ->with('workspace')
            ->withCount('policies')
            ->withMax('policies as last_policy_sync_at', 'last_synced_at');
    }

    public static function getGlobalSearchEloquentQuery(): Builder
    {
        return static::getEloquentQuery()->whereRaw('1 = 0');
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort(function (Builder $query, string $direction, mixed $livewire): Builder {
                if (static::triageSortIsWorstFirst(static::triageSortState($livewire))) {
                    return static::applyWorstFirstTriageOrdering($query);
                }

                $nameColumn = (new ManagedEnvironment)->qualifyColumn('name');

                if (! method_exists($livewire, 'getTableSortColumn') || $livewire->getTableSortColumn() !== 'name') {
                    $query->orderBy($nameColumn, $direction);
                }

                return $query;
            })
            ->paginated(TablePaginationProfiles::resource())
            ->persistFiltersInSession()
            ->persistSearchInSession()
            ->persistSortInSession()
            ->recordUrl(fn (ManagedEnvironment $record): string => static::getUrl('view', ['record' => $record]))
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('backup_posture')
                    ->label('Backup posture')
                    ->badge()
                    ->state(fn (ManagedEnvironment $record): ?string => static::backupHealthAssessmentForTenant($record)?->posture)
                    ->formatStateUsing(fn (mixed $state, ManagedEnvironment $record): string => TenantRecoveryTriagePresentation::backupPostureLabel(
                        static::backupHealthAssessmentForTenant($record),
                    ))
                    ->color(fn (ManagedEnvironment $record): string => TenantRecoveryTriagePresentation::backupPostureTone(
                        static::backupHealthAssessmentForTenant($record),
                    )),
                Tables\Columns\TextColumn::make('recovery_evidence')
                    ->label('Recovery evidence')
                    ->badge()
                    ->state(fn (ManagedEnvironment $record): ?string => TenantRecoveryTriagePresentation::recoveryEvidenceState(
                        static::recoveryEvidenceForTenant($record),
                    ))
                    ->formatStateUsing(fn (mixed $state, ManagedEnvironment $record): string => TenantRecoveryTriagePresentation::recoveryEvidenceLabel(
                        static::recoveryEvidenceForTenant($record),
                    ))
                    ->color(fn (ManagedEnvironment $record): string => TenantRecoveryTriagePresentation::recoveryEvidenceTone(
                        static::recoveryEvidenceForTenant($record),
                    )),
                Tables\Columns\TextColumn::make('review_state')
                    ->label('Review state')
                    ->badge()
                    ->state(fn (ManagedEnvironment $record, mixed $livewire): ?string => static::selectedTriageReviewRowForTenant(
                        $record,
                        static::currentPortfolioTriageState($livewire),
                    )['derived_state'] ?? null)
                    ->formatStateUsing(BadgeRenderer::label(BadgeDomain::ManagedEnvironmentTriageReviewState))
                    ->color(BadgeRenderer::color(BadgeDomain::ManagedEnvironmentTriageReviewState))
                    ->icon(BadgeRenderer::icon(BadgeDomain::ManagedEnvironmentTriageReviewState))
                    ->iconColor(BadgeRenderer::iconColor(BadgeDomain::ManagedEnvironmentTriageReviewState))
                    ->description(fn (ManagedEnvironment $record, mixed $livewire): ?string => static::triageReviewDescriptionForTenant(
                        $record,
                        static::currentPortfolioTriageState($livewire),
                    )),
                Tables\Columns\TextColumn::make('managed_environment_id')
                    ->label('ManagedEnvironment ID')
                    ->copyable()
                    ->searchable(['slug'])
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('environment')
                    ->badge()
                    ->formatStateUsing(TagBadgeRenderer::label(TagBadgeDomain::TenantEnvironment))
                    ->color(TagBadgeRenderer::color(TagBadgeDomain::TenantEnvironment))
                    ->sortable(['kind']),
                Tables\Columns\TextColumn::make('policies_count')
                    ->label('Policies')
                    ->numeric()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('last_policy_sync_at')
                    ->label('Last Sync')
                    ->since()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('domain')
                    ->copyable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\IconColumn::make('is_current')
                    ->label('Current')
                    ->boolean()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('status')
                    ->badge()
                    ->formatStateUsing(BadgeRenderer::label(BadgeDomain::TenantStatus))
                    ->color(BadgeRenderer::color(BadgeDomain::TenantStatus))
                    ->icon(BadgeRenderer::icon(BadgeDomain::TenantStatus))
                    ->iconColor(BadgeRenderer::iconColor(BadgeDomain::TenantStatus))
                    ->description(fn (ManagedEnvironment $record): string => static::tenantLifecyclePresentation($record)->shortDescription)
                    ->sortable(),
                Tables\Columns\TextColumn::make('workspace_posture')
                    ->label('Workspace posture')
                    ->badge()
                    ->state(fn (ManagedEnvironment $record): string => app(WorkspaceLifecycleService::class)->tenantPosture($record))
                    ->formatStateUsing(BadgeRenderer::label(BadgeDomain::TenantWorkspacePosture))
                    ->color(BadgeRenderer::color(BadgeDomain::TenantWorkspacePosture))
                    ->icon(BadgeRenderer::icon(BadgeDomain::TenantWorkspacePosture))
                    ->iconColor(BadgeRenderer::iconColor(BadgeDomain::TenantWorkspacePosture))
                    ->description(fn (ManagedEnvironment $record): ?string => $record->isRemovedFromWorkspace()
                        ? 'Hidden from active tenant context; historical records remain available.'
                        : null),
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->since()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\TrashedFilter::make()
                    ->label('Archived')
                    ->placeholder('Active')
                    ->trueLabel('All')
                    ->falseLabel('Archived')
                    ->default(true),
                Tables\Filters\SelectFilter::make('environment')
                    ->attribute('kind')
                    ->options([
                        'prod' => 'PROD',
                        'dev' => 'DEV',
                        'staging' => 'STAGING',
                        'other' => 'Other',
                    ]),
                Tables\Filters\SelectFilter::make('backup_posture')
                    ->label('Backup posture')
                    ->multiple()
                    ->options(TenantRecoveryTriagePresentation::backupPostureOptions())
                    ->query(function (Builder $query, array $data): Builder {
                        return static::applySnapshotTenantSubsetFilter(
                            $query,
                            static::sanitizeBackupPostures($data['values'] ?? []),
                            snapshotKey: 'backup_posture_ids',
                        );
                    }),
                Tables\Filters\SelectFilter::make('recovery_evidence')
                    ->label('Recovery evidence')
                    ->multiple()
                    ->options(TenantRecoveryTriagePresentation::recoveryEvidenceOptions())
                    ->query(function (Builder $query, array $data): Builder {
                        return static::applyRecoveryEvidenceFilter(
                            $query,
                            static::sanitizeRecoveryEvidenceStates($data['values'] ?? []),
                        );
                    }),
                Tables\Filters\SelectFilter::make('review_state')
                    ->label('Review state')
                    ->multiple()
                    ->options(static::reviewStateOptions())
                    ->query(function (Builder $query, array $data, mixed $livewire): Builder {
                        return static::applyReviewStateFilter(
                            $query,
                            static::sanitizeReviewStates($data['values'] ?? []),
                            static::currentPortfolioTriageState($livewire),
                        );
                    }),
                Tables\Filters\SelectFilter::make('triage_sort')
                    ->label('Sort order')
                    ->options(TenantRecoveryTriagePresentation::triageSortOptions())
                    ->placeholder('Default order')
                    ->query(static fn (Builder $query): Builder => $query),
            ])
            ->actions([
                Actions\Action::make('related_onboarding')
                    ->label(fn (ManagedEnvironment $record): string => static::relatedOnboardingDraftActionLabel($record, TenantActionSurface::TenantIndexRow) ?? 'Resume onboarding')
                    ->icon(fn (ManagedEnvironment $record): string => static::relatedOnboardingDraftAction($record, TenantActionSurface::TenantIndexRow)?->icon ?? 'heroicon-o-arrow-path')
                    ->url(fn (ManagedEnvironment $record): string => static::relatedOnboardingDraftUrl($record) ?? route('admin.onboarding'))
                    ->visible(fn (ManagedEnvironment $record): bool => static::tenantIndexPrimaryAction($record)?->key === 'related_onboarding'),
                    Actions\Action::make('openTenant')
                        ->label('Open')
                        ->icon('heroicon-o-arrow-right')
                        ->color('primary')
                        ->url(function (?ManagedEnvironment $record = null, mixed $livewire = null): string {
                        if (! $record instanceof ManagedEnvironment) {
                            return '#';
                        }

                        $triageState = $livewire instanceof Pages\ListManagedEnvironments
                            ? static::currentPortfolioTriageState($livewire)
                            : [];

                        if (! static::hasActivePortfolioTriageState(
                            static::sanitizeBackupPostures($triageState['backup_posture'] ?? []),
                            static::sanitizeRecoveryEvidenceStates($triageState['recovery_evidence'] ?? []),
                            static::sanitizeReviewStates($triageState['review_state'] ?? []),
                            static::sanitizeTriageSort($triageState['triage_sort'] ?? null),
                        )) {
                            $triageState = static::portfolioReturnFiltersFromRequest(request()->query());
                        }

                        return static::tenantDashboardOpenUrl($record, $triageState);
                    })
                    ->visible(fn (ManagedEnvironment $record): bool => $record->isActive() && static::tenantIndexPrimaryAction($record)?->key !== 'related_onboarding'),
                ActionGroup::make([
                    Actions\Action::make('related_onboarding_overflow')
                        ->label(fn (ManagedEnvironment $record): string => static::relatedOnboardingDraftActionLabel($record, TenantActionSurface::TenantIndexRow) ?? 'View related onboarding')
                        ->icon(fn (ManagedEnvironment $record): string => static::relatedOnboardingDraftAction($record, TenantActionSurface::TenantIndexRow)?->icon ?? 'heroicon-o-eye')
                        ->url(fn (ManagedEnvironment $record): string => static::relatedOnboardingDraftUrl($record) ?? route('admin.onboarding'))
                        ->visible(fn (ManagedEnvironment $record): bool => static::relatedOnboardingDraftAction($record, TenantActionSurface::TenantIndexRow) instanceof TenantActionDescriptor
                            && static::tenantIndexPrimaryAction($record)?->key !== 'related_onboarding'),
                    Actions\Action::make('compareEnvironments')
                        ->label('Compare tenants')
                        ->icon('heroicon-o-scale')
                        ->color('gray')
                        ->url(function (ManagedEnvironment $record, mixed $livewire): string {
                            $triageState = $livewire instanceof Pages\ListManagedEnvironments
                                ? static::currentPortfolioTriageState($livewire)
                                : [];

                            if (! static::hasActivePortfolioTriageState(
                                static::sanitizeBackupPostures($triageState['backup_posture'] ?? []),
                                static::sanitizeRecoveryEvidenceStates($triageState['recovery_evidence'] ?? []),
                                static::sanitizeReviewStates($triageState['review_state'] ?? []),
                                static::sanitizeTriageSort($triageState['triage_sort'] ?? null),
                            )) {
                                $triageState = static::portfolioReturnFiltersFromRequest(request()->query());
                            }

                            return static::crossEnvironmentCompareOpenUrl($record, $triageState);
                        })
                        ->visible(fn (ManagedEnvironment $record): bool => static::crossEnvironmentCompareActionVisible($record)),
                    UiEnforcement::forAction(
                        Actions\Action::make('edit')
                            ->label('Edit')
                            ->icon('heroicon-o-pencil-square')
                            ->visible(fn (ManagedEnvironment $record): bool => static::canEdit($record))
                            ->url(fn (ManagedEnvironment $record) => static::getUrl('edit', ['record' => $record]))
                    )
                        ->requireCapability(Capabilities::TENANT_MANAGE)
                        ->apply(),
                    static::makeAdminConsentAction(),
                    static::makeOpenInEntraAction(),
                    static::makeSyncTenantAction(),
                    static::makeVerifyConfigurationAction(),
                    Actions\Action::make('markReviewed')
                        ->label('Mark reviewed')
                        ->icon('heroicon-o-check-circle')
                        ->color('success')
                        ->requiresConfirmation()
                        ->modalHeading('Mark reviewed')
                        ->modalDescription(fn (ManagedEnvironment $record, mixed $livewire): string => static::triageReviewActionModalDescription(
                            $record,
                            static::currentPortfolioTriageState($livewire),
                            ManagedEnvironmentTriageReview::STATE_REVIEWED,
                        ))
                        ->visible(fn (ManagedEnvironment $record, mixed $livewire): bool => static::selectedTriageReviewRowForTenant(
                            $record,
                            static::currentPortfolioTriageState($livewire),
                        ) !== null && static::userCanSeeTriageReviewAction($record))
                        ->disabled(fn (ManagedEnvironment $record): bool => static::triageReviewActionIsDisabled($record))
                        ->tooltip(fn (ManagedEnvironment $record): ?string => static::triageReviewActionTooltip($record))
                        ->before(function (ManagedEnvironment $record): void {
                            static::authorizeTriageReviewAction($record);
                        })
                        ->action(function (
                            ManagedEnvironment $record,
                            mixed $livewire,
                            ManagedEnvironmentTriageReviewService $service,
                        ): void {
                            static::handleTriageReviewMutation(
                                tenant: $record,
                                triageState: static::currentPortfolioTriageState($livewire),
                                targetManualState: ManagedEnvironmentTriageReview::STATE_REVIEWED,
                                service: $service,
                            );
                        }),
                    Actions\Action::make('markFollowUpNeeded')
                        ->label('Mark follow-up needed')
                        ->icon('heroicon-o-exclamation-triangle')
                        ->color('warning')
                        ->requiresConfirmation()
                        ->modalHeading('Mark follow-up needed')
                        ->modalDescription(fn (ManagedEnvironment $record, mixed $livewire): string => static::triageReviewActionModalDescription(
                            $record,
                            static::currentPortfolioTriageState($livewire),
                            ManagedEnvironmentTriageReview::STATE_FOLLOW_UP_NEEDED,
                        ))
                        ->visible(fn (ManagedEnvironment $record, mixed $livewire): bool => static::selectedTriageReviewRowForTenant(
                            $record,
                            static::currentPortfolioTriageState($livewire),
                        ) !== null && static::userCanSeeTriageReviewAction($record))
                        ->disabled(fn (ManagedEnvironment $record): bool => static::triageReviewActionIsDisabled($record))
                        ->tooltip(fn (ManagedEnvironment $record): ?string => static::triageReviewActionTooltip($record))
                        ->before(function (ManagedEnvironment $record): void {
                            static::authorizeTriageReviewAction($record);
                        })
                        ->action(function (
                            ManagedEnvironment $record,
                            mixed $livewire,
                            ManagedEnvironmentTriageReviewService $service,
                        ): void {
                            static::handleTriageReviewMutation(
                                tenant: $record,
                                triageState: static::currentPortfolioTriageState($livewire),
                                targetManualState: ManagedEnvironmentTriageReview::STATE_FOLLOW_UP_NEEDED,
                                service: $service,
                            );
                        }),
                    static::makeRestoreTenantAction(TenantActionSurface::TenantIndexRow),
                    static::makeRestoreTenantToWorkspaceAction(),
                    static::rbacAction(),
                    UiEnforcement::forAction(
                        Actions\Action::make('forceDelete')
                            ->label('Force delete')
                            ->color('danger')
                            ->icon('heroicon-o-trash')
                            ->requiresConfirmation()
                            ->visible(fn (?ManagedEnvironment $record): bool => (bool) $record?->trashed())
                            ->action(function (?ManagedEnvironment $record, AuditLogger $auditLogger): void {
                                if ($record === null) {
                                    return;
                                }

                                $user = auth()->user();

                                if (! $user instanceof User) {
                                    abort(403);
                                }

                                /** @var CapabilityResolver $resolver */
                                $resolver = app(CapabilityResolver::class);

                                if (! $resolver->can($user, $record, Capabilities::TENANT_DELETE)) {
                                    abort(403);
                                }

                                $tenant = ManagedEnvironment::withTrashed()->find($record->id);

                                if (! $tenant?->trashed()) {
                                    Notification::make()
                                        ->title('ManagedEnvironment must be archived first')
                                        ->danger()
                                        ->send();

                                    return;
                                }

                                $auditLogger->log(
                                    tenant: $tenant,
                                    action: 'tenant.force_deleted',
                                    resourceType: 'tenant',
                                    resourceId: (string) $tenant->id,
                                    status: 'success',
                                    context: ['metadata' => ['managed_environment_id' => $tenant->managed_environment_id]]
                                );

                                $tenant->forceDelete();

                                Notification::make()
                                    ->title('ManagedEnvironment permanently deleted')
                                    ->success()
                                    ->send();
                            }),
                    )
                        ->preserveVisibility()
                        ->requireCapability(Capabilities::TENANT_DELETE)
                        ->apply(),
                    static::makeRemoveTenantFromWorkspaceAction(),
                    static::makeArchiveTenantAction(TenantActionSurface::TenantIndexRow),
                ])
                    ->label('More')
                    ->icon('heroicon-o-ellipsis-vertical')
                    ->color('gray'),
            ])
            ->bulkActions([
                BulkActionGroup::make([
                    Actions\BulkAction::make('compareSelected')
                        ->label('Compare selected')
                        ->icon('heroicon-o-scale')
                        ->color('gray')
                        ->visible(fn (): bool => auth()->user() instanceof User)
                        ->authorize(fn (): bool => auth()->user() instanceof User)
                        ->extraAttributes(fn (mixed $livewire): array => [
                            'x-bind:aria-disabled' => static::crossEnvironmentCompareBulkClientDisabledExpression($livewire).' ? true : null',
                            'x-bind:disabled' => static::crossEnvironmentCompareBulkClientDisabledExpression($livewire),
                            'x-bind:title' => static::crossEnvironmentCompareBulkClientTooltipExpression($livewire),
                            'x-bind:class' => "{ 'fi-disabled': ".static::crossEnvironmentCompareBulkClientDisabledExpression($livewire).' }',
                        ])
                        ->action(function (Collection $records, mixed $livewire): void {
                            $disabledReason = static::crossEnvironmentCompareBulkDisabledReason($records);

                            if ($disabledReason !== null) {
                                Notification::make()
                                    ->title($disabledReason)
                                    ->danger()
                                    ->send();

                                return;
                            }

                            if (method_exists($livewire, 'redirect')) {
                                $livewire->redirect(static::crossEnvironmentCompareBulkOpenUrl($records, $livewire), navigate: true);
                            }
                        }),
                    Actions\BulkAction::make('syncSelected')
                        ->label('Sync selected')
                        ->icon('heroicon-o-arrow-path')
                        ->color('warning')
                        ->requiresConfirmation()
                        ->visible(fn (): bool => auth()->user() instanceof User)
                        ->authorize(fn (): bool => auth()->user() instanceof User)
                        ->disabled(function (Collection $records): bool {
                            $user = auth()->user();

                            if (! $user instanceof User) {
                                return true;
                            }

                            if ($records->isEmpty()) {
                                return true;
                            }

                            /** @var CapabilityResolver $resolver */
                            $resolver = app(CapabilityResolver::class);

                            return $records
                                ->filter(fn ($record) => $record instanceof ManagedEnvironment)
                                ->contains(fn (ManagedEnvironment $tenant): bool => ! $resolver->can($user, $tenant, Capabilities::TENANT_SYNC));
                        })
                        ->tooltip(function (Collection $records): ?string {
                            $user = auth()->user();

                            if (! $user instanceof User) {
                                return UiTooltips::insufficientPermission();
                            }

                            if ($records->isEmpty()) {
                                return null;
                            }

                            /** @var CapabilityResolver $resolver */
                            $resolver = app(CapabilityResolver::class);

                            $isDenied = $records
                                ->filter(fn ($record) => $record instanceof ManagedEnvironment)
                                ->contains(fn (ManagedEnvironment $tenant): bool => ! $resolver->can($user, $tenant, Capabilities::TENANT_SYNC));

                            return $isDenied ? UiTooltips::insufficientPermission() : null;
                        })
                        ->action(function (Collection $records, AuditLogger $auditLogger): void {
                            $user = auth()->user();

                            if (! $user instanceof User) {
                                return;
                            }

                            /** @var CapabilityResolver $resolver */
                            $resolver = app(CapabilityResolver::class);

                            $eligible = $records
                                ->filter(fn ($record) => $record instanceof ManagedEnvironment && $record->isActive())
                                ->filter(fn (ManagedEnvironment $tenant) => $resolver->can($user, $tenant, Capabilities::TENANT_SYNC));

                            if ($eligible->isEmpty()) {
                                Notification::make()
                                    ->title('Bulk sync skipped')
                                    ->body('No eligible tenants selected.')
                                    ->icon('heroicon-o-information-circle')
                                    ->info()
                                    ->send();

                                return;
                            }

                            $tenantContext = ManagedEnvironment::current() ?? $eligible->first();

                            if (! $tenantContext) {
                                return;
                            }

                            $ids = $eligible->pluck('id')->toArray();
                            $count = $eligible->count();

                            /** @var BulkSelectionIdentity $selection */
                            $selection = app(BulkSelectionIdentity::class);
                            $selectionIdentity = $selection->fromIds($ids);

                            /** @var OperationRunService $runs */
                            $runs = app(OperationRunService::class);

                            $opRun = $runs->enqueueBulkOperation(
                                tenant: $tenantContext,
                                type: 'tenant.sync',
                                targetScope: [
                                    'entra_tenant_id' => (string) ($tenantContext->managed_environment_id ?? $tenantContext->external_id),
                                ],
                                selectionIdentity: $selectionIdentity,
                                dispatcher: function ($operationRun) use ($tenantContext, $user, $ids): void {
                                    BulkTenantSyncJob::dispatch(
                                        tenantId: (int) $tenantContext->getKey(),
                                        userId: (int) $user->getKey(),
                                        tenantIds: $ids,
                                        operationRun: $operationRun,
                                    );
                                },
                                initiator: $user,
                                extraContext: [
                                    'tenant_count' => $count,
                                ],
                                emitQueuedNotification: false,
                            );

                            OperationUxPresenter::queuedToast('tenant.sync')
                                ->actions([
                                    Actions\Action::make('view_run')
                                        ->label(OperationRunLinks::openLabel())
                                        ->url(OperationRunLinks::view($opRun, $tenantContext)),
                                ])
                                ->send();
                        })
                        ->deselectRecordsAfterCompletion(),
                ])->label('More'),
            ])
            ->headerActions([])
            ->emptyStateHeading('No tenants connected')
            ->emptyStateDescription('Add a tenant to start syncing inventory, policies, and provider health into this workspace.')
            ->emptyStateIcon('heroicon-o-building-office-2');
    }

    /**
     * @return list<string>
     */
    public static function sanitizeBackupPostures(mixed $value): array
    {
        return static::sanitizeRequestedValues(
            $value,
            array_keys(TenantRecoveryTriagePresentation::backupPostureOptions()),
        );
    }

    /**
     * @return list<string>
     */
    public static function sanitizeRecoveryEvidenceStates(mixed $value): array
    {
        return static::sanitizeRequestedValues(
            $value,
            array_keys(TenantRecoveryTriagePresentation::recoveryEvidenceOptions()),
        );
    }

    /**
     * @return list<string>
     */
    public static function sanitizeReviewStates(mixed $value): array
    {
        return static::sanitizeRequestedValues(
            $value,
            ManagedEnvironmentTriageReview::DERIVED_STATES,
        );
    }

    public static function sanitizeTriageSort(mixed $value): ?string
    {
        if (! is_string($value) || ! isset(self::TRIAGE_SORT_VALUES[$value])) {
            return null;
        }

        return $value;
    }

    /**
     * @param  array{
     *     backup_posture?: list<string>,
     *     recovery_evidence?: list<string>,
     *     review_state?: list<string>,
     *     triage_sort?: string|null
     * }  $triageState
     */
    public static function tenantDashboardOpenUrl(ManagedEnvironment $record, array $triageState = []): string
    {
        $arrivalState = static::portfolioArrivalStateForTenant($record, $triageState);

        if ($arrivalState === null) {
            return ManagedEnvironmentLinks::viewUrl($record);
        }

        return ManagedEnvironmentLinks::viewUrl($record, [
            PortfolioArrivalContextToken::QUERY_PARAMETER => PortfolioArrivalContextToken::encode($arrivalState),
        ]);
    }

    /**
     * @param  array{
     *     backup_posture?: list<string>,
     *     recovery_evidence?: list<string>,
     *     review_state?: list<string>,
     *     triage_sort?: string|null
     * }  $triageState
     */
    public static function crossEnvironmentCompareOpenUrl(ManagedEnvironment $record, array $triageState = []): string
    {
        return static::crossEnvironmentCompareOpenUrlForSelection(
            targetEnvironment: $record,
            triageState: $triageState,
        );
    }

    /**
     * @param  array{
     *     backup_posture?: list<string>,
     *     recovery_evidence?: list<string>,
     *     review_state?: list<string>,
     *     triage_sort?: string|null
     * }  $triageState
     */
    public static function crossEnvironmentCompareOpenUrlForSelection(
        ManagedEnvironment $targetEnvironment,
        array $triageState = [],
        ?ManagedEnvironment $sourceEnvironment = null,
    ): string {
        $normalizedState = static::portfolioReturnFilters(
            static::sanitizeBackupPostures($triageState['backup_posture'] ?? []),
            static::sanitizeRecoveryEvidenceStates($triageState['recovery_evidence'] ?? []),
            static::sanitizeReviewStates($triageState['review_state'] ?? []),
            static::sanitizeTriageSort($triageState['triage_sort'] ?? null),
        );

        return CrossEnvironmentComparePage::launchUrl(
            sourceEnvironment: $sourceEnvironment,
            targetEnvironment: $targetEnvironment,
            navigationContext: CanonicalNavigationContext::forTenantRegistry(
                backLinkUrl: static::getUrl(panel: 'admin', parameters: $normalizedState),
                tenantId: $sourceEnvironment instanceof ManagedEnvironment ? null : (int) $targetEnvironment->getKey(),
            ),
        );
    }

    /**
     * @param  array{
     *     backup_posture?: list<string>,
     *     recovery_evidence?: list<string>,
     *     review_state?: list<string>,
     *     triage_sort?: string|null
     * }  $triageState
     * @return array<string, mixed>|null
     */
    private static function portfolioArrivalStateForTenant(ManagedEnvironment $record, array $triageState = []): ?array
    {
        $backupPostures = static::sanitizeBackupPostures($triageState['backup_posture'] ?? []);
        $recoveryEvidenceFilters = static::sanitizeRecoveryEvidenceStates($triageState['recovery_evidence'] ?? []);
        $reviewStates = static::sanitizeReviewStates($triageState['review_state'] ?? []);
        $triageSort = static::sanitizeTriageSort($triageState['triage_sort'] ?? null);

        if (! static::hasActivePortfolioTriageState($backupPostures, $recoveryEvidenceFilters, $reviewStates, $triageSort)) {
            return null;
        }

        $selectedReviewRow = static::selectedTriageReviewRowForTenant(
            $record,
            static::portfolioReturnFilters(
                $backupPostures,
                $recoveryEvidenceFilters,
                $reviewStates,
                $triageSort,
            ),
        );

        if ($selectedReviewRow === null) {
            return null;
        }
        $workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());

        return [
            'sourceSurface' => PortfolioArrivalContextToken::SOURCE_TENANT_REGISTRY,
            'tenantRouteKey' => filled($record->external_id) ? (string) $record->external_id : (string) $record->getKey(),
            'workspaceId' => $workspaceId,
            'concernFamily' => $selectedReviewRow['concern_family'],
            'concernState' => $selectedReviewRow['current_state'],
            'concernReason' => $selectedReviewRow['current_snapshot']['reasonCode'] ?? null,
            'returnFilters' => static::portfolioReturnFilters($backupPostures, $recoveryEvidenceFilters, $reviewStates, $triageSort),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    public static function portfolioReturnFilters(
        array $backupPostures,
        array $recoveryEvidence,
        array $reviewStates,
        ?string $triageSort,
    ): array {
        $filters = [];

        if ($backupPostures !== []) {
            $filters['backup_posture'] = $backupPostures;
        }

        if ($recoveryEvidence !== []) {
            $filters['recovery_evidence'] = $recoveryEvidence;
        }

        if ($reviewStates !== []) {
            $filters['review_state'] = $reviewStates;
        }

        if ($triageSort !== null) {
            $filters['triage_sort'] = $triageSort;
        }

        return $filters;
    }

    /**
     * @param  array<string, mixed>  $query
     * @return array<string, mixed>
     */
    private static function portfolioReturnFiltersFromRequest(array $query): array
    {
        return static::portfolioReturnFilters(
            static::sanitizeBackupPostures($query['backup_posture'] ?? []),
            static::sanitizeRecoveryEvidenceStates($query['recovery_evidence'] ?? []),
            static::sanitizeReviewStates($query['review_state'] ?? []),
            static::sanitizeTriageSort($query['triage_sort'] ?? null),
        );
    }

    private static function crossEnvironmentCompareActionVisible(ManagedEnvironment $record): bool
    {
        if (! $record->isActive()) {
            return false;
        }

        $user = auth()->user();

        if (! $user instanceof User) {
            return false;
        }

        $workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());

        if (! is_int($workspaceId) || $workspaceId !== (int) $record->workspace_id) {
            return false;
        }

        $workspace = Workspace::query()->whereKey($workspaceId)->first();

        if (! $workspace instanceof Workspace) {
            return false;
        }

        /** @var WorkspaceCapabilityResolver $workspaceResolver */
        $workspaceResolver = app(WorkspaceCapabilityResolver::class);

        if (! $workspaceResolver->isMember($user, $workspace)
            || ! $workspaceResolver->can($user, $workspace, Capabilities::WORKSPACE_BASELINES_VIEW)) {
            return false;
        }

        /** @var CapabilityResolver $tenantResolver */
        $tenantResolver = app(CapabilityResolver::class);

        return $user->canAccessTenant($record)
            && $tenantResolver->can($user, $record, Capabilities::TENANT_VIEW);
    }

    private static function crossEnvironmentCompareBulkDisabledReason(Collection $records): ?string
    {
        $user = auth()->user();

        if (! $user instanceof User) {
            return UiTooltips::insufficientPermission();
        }

        $environments = $records
            ->filter(fn ($record): bool => $record instanceof ManagedEnvironment)
            ->values();

        if ($records->count() !== 2 || $environments->count() !== 2) {
            return 'Select exactly two environments to compare.';
        }

        if ($environments->contains(fn (ManagedEnvironment $environment): bool => ! $environment->isActive())) {
            return 'Only active environments can be compared.';
        }

        $workspaceIds = $environments
            ->map(fn (ManagedEnvironment $environment): int => (int) $environment->workspace_id)
            ->unique()
            ->values();

        if ($workspaceIds->count() !== 1) {
            return UiTooltips::insufficientPermission();
        }

        $workspaceId = $workspaceIds->first();

        $workspace = Workspace::query()->whereKey($workspaceId)->first();

        if (! $workspace instanceof Workspace) {
            return UiTooltips::insufficientPermission();
        }

        /** @var WorkspaceCapabilityResolver $workspaceResolver */
        $workspaceResolver = app(WorkspaceCapabilityResolver::class);

        if (! $workspaceResolver->isMember($user, $workspace)
            || ! $workspaceResolver->can($user, $workspace, Capabilities::WORKSPACE_BASELINES_VIEW)) {
            return UiTooltips::insufficientPermission();
        }

        /** @var CapabilityResolver $environmentResolver */
        $environmentResolver = app(CapabilityResolver::class);

        $isDenied = $environments->contains(fn (ManagedEnvironment $environment): bool => ! $user->canAccessTenant($environment)
            || ! $environmentResolver->can($user, $environment, Capabilities::TENANT_VIEW));

        return $isDenied ? UiTooltips::insufficientPermission() : null;
    }

    private static function crossEnvironmentCompareBulkClientDisabledExpression(mixed $livewire): string
    {
        $containsInactiveSelection = static::crossEnvironmentCompareBulkContainsInactiveSelectionExpression($livewire);

        return "getSelectedRecordsCount() !== 2 || {$containsInactiveSelection}";
    }

    private static function crossEnvironmentCompareBulkClientTooltipExpression(mixed $livewire): string
    {
        $containsInactiveSelection = static::crossEnvironmentCompareBulkContainsInactiveSelectionExpression($livewire);

        return "getSelectedRecordsCount() !== 2 ? 'Select exactly two environments to compare.' : ({$containsInactiveSelection} ? 'Only active environments can be compared.' : null)";
    }

    private static function crossEnvironmentCompareBulkContainsInactiveSelectionExpression(mixed $livewire): string
    {
        $inactiveRecordKeys = \Illuminate\Support\Js::from(static::crossEnvironmentCompareInactiveSelectionRecordKeys($livewire));

        return "[...selectedRecords].some((key) => {$inactiveRecordKeys}.includes(key))";
    }

    /**
     * @return list<string>
     */
    private static function crossEnvironmentCompareInactiveSelectionRecordKeys(mixed $livewire): array
    {
        if (! $livewire instanceof HasTable || ! method_exists($livewire, 'getTableRecordKey')) {
            return [];
        }

        $tableRecords = $livewire->getTableRecords();

        if (method_exists($tableRecords, 'getCollection')) {
            $tableRecords = $tableRecords->getCollection();
        }

        return collect($tableRecords)
            ->filter(fn ($record): bool => $record instanceof ManagedEnvironment && ! $record->isActive())
            ->map(fn (ManagedEnvironment $tenant): string => (string) $livewire->getTableRecordKey($tenant))
            ->values()
            ->all();
    }

    private static function crossEnvironmentCompareBulkOpenUrl(Collection $records, mixed $livewire): string
    {
        $triageState = $livewire instanceof Pages\ListManagedEnvironments
            ? static::currentPortfolioTriageState($livewire)
            : [];

        if (! static::hasActivePortfolioTriageState(
            static::sanitizeBackupPostures($triageState['backup_posture'] ?? []),
            static::sanitizeRecoveryEvidenceStates($triageState['recovery_evidence'] ?? []),
            static::sanitizeReviewStates($triageState['review_state'] ?? []),
            static::sanitizeTriageSort($triageState['triage_sort'] ?? null),
        )) {
            $triageState = static::portfolioReturnFiltersFromRequest(request()->query());
        }

        $tenants = $records
            ->filter(fn ($record): bool => $record instanceof ManagedEnvironment)
            ->values();

        return static::crossEnvironmentCompareOpenUrlForSelection(
            targetEnvironment: $tenants->get(1),
            triageState: $triageState,
            sourceEnvironment: $tenants->get(0),
        );
    }

    private static function hasActivePortfolioTriageState(
        array $backupPostures,
        array $recoveryEvidence,
        array $reviewStates,
        ?string $triageSort,
    ): bool {
        return $backupPostures !== []
            || $recoveryEvidence !== []
            || $reviewStates !== []
            || $triageSort === TenantRecoveryTriagePresentation::TRIAGE_SORT_WORST_FIRST;
    }

    public static function portfolioConcernPriority(string $family, string $state): int
    {
        return match (true) {
            $family === 'backup_health' && $state === TenantBackupHealthAssessment::POSTURE_ABSENT => 1,
            $family === 'recovery_evidence' && $state === TenantRecoveryTriagePresentation::RECOVERY_EVIDENCE_WEAKENED => 2,
            $family === 'backup_health' && $state === TenantBackupHealthAssessment::POSTURE_STALE => 3,
            $family === 'recovery_evidence' && $state === TenantRecoveryTriagePresentation::RECOVERY_EVIDENCE_UNVALIDATED => 4,
            $family === 'backup_health' && $state === TenantBackupHealthAssessment::POSTURE_DEGRADED => 5,
            default => 99,
        };
    }

    /**
     * @param  list<string>  $allowedValues
     * @return list<string>
     */
    private static function sanitizeRequestedValues(mixed $value, array $allowedValues): array
    {
        $allowed = array_fill_keys($allowedValues, true);

        return array_values(array_filter(
            array_unique(array_filter(static::normalizeRequestedValues($value), static fn (string $item): bool => isset($allowed[$item]))),
            static fn (string $item): bool => isset($allowed[$item]),
        ));
    }

    /**
     * @return list<string>
     */
    private static function normalizeRequestedValues(mixed $value): array
    {
        if (is_string($value) && $value !== '') {
            return [$value];
        }

        if (! is_array($value)) {
            return [];
        }

        return array_values(array_filter($value, static fn (mixed $item): bool => is_string($item) && $item !== ''));
    }

    private static function triageSortState(mixed $livewire): ?string
    {
        if (! is_object($livewire) || ! method_exists($livewire, 'getTableFilterState')) {
            return null;
        }

        $state = $livewire->getTableFilterState('triage_sort');
        $value = is_array($state) ? ($state['value'] ?? null) : null;

        return static::sanitizeTriageSort($value);
    }

    /**
     * @return list<string>
     */
    private static function backupPostureState(mixed $livewire): array
    {
        if (! is_object($livewire) || ! method_exists($livewire, 'getTableFilterState')) {
            return [];
        }

        $state = $livewire->getTableFilterState('backup_posture');
        $values = is_array($state) ? ($state['values'] ?? []) : [];

        return static::sanitizeBackupPostures($values);
    }

    /**
     * @return list<string>
     */
    private static function recoveryEvidenceState(mixed $livewire): array
    {
        if (! is_object($livewire) || ! method_exists($livewire, 'getTableFilterState')) {
            return [];
        }

        $state = $livewire->getTableFilterState('recovery_evidence');
        $values = is_array($state) ? ($state['values'] ?? []) : [];

        return static::sanitizeRecoveryEvidenceStates($values);
    }

    /**
     * @return list<string>
     */
    private static function reviewStateState(mixed $livewire): array
    {
        if (! is_object($livewire) || ! method_exists($livewire, 'getTableFilterState')) {
            return [];
        }

        $state = $livewire->getTableFilterState('review_state');
        $values = is_array($state) ? ($state['values'] ?? []) : [];

        return static::sanitizeReviewStates($values);
    }

    /**
     * @return array{
     *     backup_posture: list<string>,
     *     recovery_evidence: list<string>,
     *     review_state: list<string>,
     *     triage_sort: string|null
     * }
     */
    public static function currentPortfolioTriageState(mixed $livewire): array
    {
        return [
            'backup_posture' => static::backupPostureState($livewire),
            'recovery_evidence' => static::recoveryEvidenceState($livewire),
            'review_state' => static::reviewStateState($livewire),
            'triage_sort' => static::triageSortState($livewire),
        ];
    }

    private static function triageSortIsWorstFirst(?string $value): bool
    {
        return $value === TenantRecoveryTriagePresentation::TRIAGE_SORT_WORST_FIRST;
    }

    private static function backupHealthAssessmentForTenant(ManagedEnvironment $tenant): ?TenantBackupHealthAssessment
    {
        return static::postureSnapshot()['backup_health'][(int) $tenant->getKey()] ?? null;
    }

    /**
     * @return array<string, mixed>|null
     */
    private static function recoveryEvidenceForTenant(ManagedEnvironment $tenant): ?array
    {
        return static::postureSnapshot()['recovery_evidence'][(int) $tenant->getKey()] ?? null;
    }

    /**
     * @return array<string, string>
     */
    private static function reviewStateOptions(): array
    {
        return collect(ManagedEnvironmentTriageReview::DERIVED_STATES)
            ->mapWithKeys(static fn (string $state): array => [
                $state => BadgeRenderer::spec(BadgeDomain::ManagedEnvironmentTriageReviewState, $state)->label,
            ])
            ->all();
    }

    /**
     * @return array{
     *     rows: array<int, array{
     *         backup_health: array<string, mixed>,
     *         recovery_evidence: array<string, mixed>
     *     }>,
     *     summaries: array<string, array{
     *         concern_family: string,
     *         affected_total: int,
     *         reviewed_count: int,
     *         follow_up_needed_count: int,
     *         changed_since_review_count: int,
     *         not_reviewed_count: int
     *     }>
     * }
     */
    private static function triageReviewSnapshot(): array
    {
        $request = request();
        $cached = $request->attributes->get(self::TRIAGE_REVIEW_SNAPSHOT_REQUEST_KEY);

        if (is_array($cached)) {
            return $cached;
        }

        $snapshot = static::postureSnapshot();
        $workspaceId = app(WorkspaceContext::class)->currentWorkspaceId($request);

        if (! is_int($workspaceId) || $workspaceId <= 0) {
            $resolved = [
                'rows' => [],
                'summaries' => [],
            ];

            $request->attributes->set(self::TRIAGE_REVIEW_SNAPSHOT_REQUEST_KEY, $resolved);

            return $resolved;
        }

        $resolved = app(ManagedEnvironmentTriageReviewStateResolver::class)->resolveMany(
            workspaceId: $workspaceId,
            tenantIds: $snapshot['tenant_ids'],
            backupHealthByTenant: $snapshot['backup_health'],
            recoveryEvidenceByTenant: $snapshot['recovery_evidence'],
        );

        $request->attributes->set(self::TRIAGE_REVIEW_SNAPSHOT_REQUEST_KEY, $resolved);

        return $resolved;
    }

    /**
     * @param  array{
     *     backup_posture?: list<string>,
     *     recovery_evidence?: list<string>,
     *     review_state?: list<string>,
     *     triage_sort?: string|null
     * }  $triageState
     * @return array<string, mixed>|null
     */
    private static function selectedTriageReviewRowForTenant(ManagedEnvironment $tenant, array $triageState = []): ?array
    {
        $rows = static::triageReviewSnapshot()['rows'][(int) $tenant->getKey()] ?? null;

        if (! is_array($rows)) {
            return null;
        }

        return static::selectedTriageReviewRow($rows, $triageState);
    }

    /**
     * @param  array{
     *     backup_health?: array<string, mixed>,
     *     recovery_evidence?: array<string, mixed>
     * }  $rows
     * @param  array{
     *     backup_posture?: list<string>,
     *     recovery_evidence?: list<string>,
     *     review_state?: list<string>,
     *     triage_sort?: string|null
     * }  $triageState
     * @return array<string, mixed>|null
     */
    private static function selectedTriageReviewRow(array $rows, array $triageState = []): ?array
    {
        $selectedFamily = static::selectedTriageReviewFamily($rows, $triageState);

        if ($selectedFamily === null) {
            return null;
        }

        $row = $rows[$selectedFamily] ?? null;

        if (! is_array($row) || ($row['current_concern_present'] ?? false) !== true) {
            return null;
        }

        $row['concern_family'] = $selectedFamily;
        $row['concern_family_label'] = static::triageConcernFamilyLabel($selectedFamily);

        return $row;
    }

    /**
     * @param  array{
     *     backup_health?: array<string, mixed>,
     *     recovery_evidence?: array<string, mixed>
     * }  $rows
     * @param  array{
     *     backup_posture?: list<string>,
     *     recovery_evidence?: list<string>,
     *     review_state?: list<string>,
     *     triage_sort?: string|null
     * }  $triageState
     */
    private static function selectedTriageReviewFamily(array $rows, array $triageState = []): ?string
    {
        $backupPostures = static::sanitizeBackupPostures($triageState['backup_posture'] ?? []);
        $recoveryEvidence = static::sanitizeRecoveryEvidenceStates($triageState['recovery_evidence'] ?? []);

        if ($backupPostures !== [] && $recoveryEvidence === []) {
            return (($rows[PortfolioArrivalContextToken::FAMILY_BACKUP_HEALTH]['current_concern_present'] ?? false) === true)
                ? PortfolioArrivalContextToken::FAMILY_BACKUP_HEALTH
                : null;
        }

        if ($backupPostures === [] && $recoveryEvidence !== []) {
            return (($rows[PortfolioArrivalContextToken::FAMILY_RECOVERY_EVIDENCE]['current_concern_present'] ?? false) === true)
                ? PortfolioArrivalContextToken::FAMILY_RECOVERY_EVIDENCE
                : null;
        }

        $candidates = [];

        foreach ([PortfolioArrivalContextToken::FAMILY_BACKUP_HEALTH, PortfolioArrivalContextToken::FAMILY_RECOVERY_EVIDENCE] as $family) {
            $row = $rows[$family] ?? null;

            if (! is_array($row) || ($row['current_concern_present'] ?? false) !== true) {
                continue;
            }

            $currentState = $row['current_state'] ?? null;

            if (! is_string($currentState) || $currentState === '') {
                continue;
            }

            $candidates[] = [
                'family' => $family,
                'priority' => static::portfolioConcernPriority($family, $currentState),
            ];
        }

        if ($candidates === []) {
            return null;
        }

        usort($candidates, static fn (array $left, array $right): int => $left['priority'] <=> $right['priority']);

        return $candidates[0]['family'];
    }

    private static function triageConcernFamilyLabel(string $concernFamily): string
    {
        return match ($concernFamily) {
            PortfolioArrivalContextToken::FAMILY_BACKUP_HEALTH => 'Backup health',
            PortfolioArrivalContextToken::FAMILY_RECOVERY_EVIDENCE => 'Recovery evidence',
            default => 'Portfolio concern',
        };
    }

    /**
     * @param  array{
     *     backup_posture?: list<string>,
     *     recovery_evidence?: list<string>,
     *     review_state?: list<string>,
     *     triage_sort?: string|null
     * }  $triageState
     */
    private static function triageReviewDescriptionForTenant(ManagedEnvironment $tenant, array $triageState = []): ?string
    {
        $row = static::selectedTriageReviewRowForTenant($tenant, $triageState);

        if ($row === null) {
            return null;
        }

        $parts = [$row['concern_family_label']];

        if (filled($row['reviewed_by_user_name'] ?? null)) {
            $parts[] = 'by '.(string) $row['reviewed_by_user_name'];
        }

        if (($row['reviewed_at'] ?? null) instanceof \Illuminate\Support\Carbon) {
            $parts[] = $row['reviewed_at']->diffForHumans();
        }

        return implode(' · ', $parts);
    }

    /**
     * @param  array{
     *     backup_posture?: list<string>,
     *     recovery_evidence?: list<string>,
     *     review_state?: list<string>,
     *     triage_sort?: string|null
     * }  $triageState
     */
    private static function triageReviewActionModalDescription(
        ManagedEnvironment $tenant,
        array $triageState,
        string $targetManualState,
    ): string {
        $row = static::selectedActionTriageReviewRowForTenant($tenant, $triageState);

        if ($row === null) {
            return 'This triage slice no longer points at a current visible concern.';
        }

        $currentLabel = BadgeRenderer::spec(BadgeDomain::ManagedEnvironmentTriageReviewState, $row['derived_state'])->label;
        $targetLabel = BadgeRenderer::spec(BadgeDomain::ManagedEnvironmentTriageReviewState, $targetManualState)->label;

        return implode("\n\n", [
            'Concern family: '.$row['concern_family_label'],
            'Current review state: '.$currentLabel,
            'Target state: '.$targetLabel,
            'Scope: TenantPilot only. This updates shared triage progress and does not change backup posture or recovery evidence.',
        ]);
    }

    private static function userCanSeeTriageReviewAction(ManagedEnvironment $tenant): bool
    {
        $user = auth()->user();

        if (! $user instanceof User) {
            return false;
        }

        return app(CapabilityResolver::class)->isMember($user, $tenant);
    }

    private static function triageReviewActionIsDisabled(ManagedEnvironment $tenant): bool
    {
        $user = auth()->user();

        if (! $user instanceof User) {
            return true;
        }

        $resolver = app(CapabilityResolver::class);

        if (! $resolver->isMember($user, $tenant)) {
            return true;
        }

        return ! $resolver->can($user, $tenant, Capabilities::MANAGED_ENVIRONMENT_TRIAGE_REVIEW_MANAGE);
    }

    private static function triageReviewActionTooltip(ManagedEnvironment $tenant): ?string
    {
        $user = auth()->user();

        if (! $user instanceof User) {
            return UiTooltips::insufficientPermission();
        }

        $resolver = app(CapabilityResolver::class);

        if ($resolver->isMember($user, $tenant) && ! $resolver->can($user, $tenant, Capabilities::MANAGED_ENVIRONMENT_TRIAGE_REVIEW_MANAGE)) {
            return UiTooltips::insufficientPermission();
        }

        return null;
    }

    private static function authorizeTriageReviewAction(ManagedEnvironment $tenant): void
    {
        $user = auth()->user();

        if (! $user instanceof User) {
            abort(403);
        }

        $resolver = app(CapabilityResolver::class);

        if (! $resolver->isMember($user, $tenant)) {
            abort(404);
        }

        if (! $resolver->can($user, $tenant, Capabilities::MANAGED_ENVIRONMENT_TRIAGE_REVIEW_MANAGE)) {
            abort(403);
        }
    }

    /**
     * @param  array{
     *     backup_posture?: list<string>,
     *     recovery_evidence?: list<string>,
     *     review_state?: list<string>,
     *     triage_sort?: string|null
     * }  $triageState
     */
    private static function handleTriageReviewMutation(
        ManagedEnvironment $tenant,
        array $triageState,
        string $targetManualState,
        ManagedEnvironmentTriageReviewService $service,
    ): void {
        $row = static::selectedActionTriageReviewRowForTenant($tenant, $triageState);

        if ($row === null) {
            Notification::make()
                ->title('No current concern to update')
                ->body('This tenant no longer belongs to the current triage slice.')
                ->warning()
                ->send();

            return;
        }

        $actor = auth()->user();
        $backupHealth = static::backupHealthAssessmentForTenant($tenant);
        $recoveryEvidence = static::recoveryEvidenceForTenant($tenant);

        $review = match ($targetManualState) {
            ManagedEnvironmentTriageReview::STATE_REVIEWED => $service->markReviewed(
                tenant: $tenant,
                concernFamily: (string) $row['concern_family'],
                backupHealth: $backupHealth,
                recoveryEvidence: $recoveryEvidence,
                actor: $actor instanceof User ? $actor : null,
            ),
            ManagedEnvironmentTriageReview::STATE_FOLLOW_UP_NEEDED => $service->markFollowUpNeeded(
                tenant: $tenant,
                concernFamily: (string) $row['concern_family'],
                backupHealth: $backupHealth,
                recoveryEvidence: $recoveryEvidence,
                actor: $actor instanceof User ? $actor : null,
            ),
            default => null,
        };

        if (! $review instanceof ManagedEnvironmentTriageReview) {
            return;
        }

        request()->attributes->remove(self::TRIAGE_REVIEW_SNAPSHOT_REQUEST_KEY);

        Notification::make()
            ->title('Review state updated')
            ->body(sprintf(
                '%s is now %s for %s.',
                $tenant->name,
                BadgeRenderer::spec(BadgeDomain::ManagedEnvironmentTriageReviewState, $review->current_state)->label,
                static::triageConcernFamilyLabel((string) $review->concern_family),
            ))
            ->success()
            ->send();
    }

    /**
     * @param  array{
     *     backup_posture?: list<string>,
     *     recovery_evidence?: list<string>,
     *     review_state?: list<string>,
     *     triage_sort?: string|null
     * }  $triageState
     * @return array<string, mixed>|null
     */
    private static function selectedActionTriageReviewRowForTenant(ManagedEnvironment $tenant, array $triageState = []): ?array
    {
        $tenantId = (int) $tenant->getKey();
        $workspaceId = (int) $tenant->workspace_id;

        if ($tenantId <= 0 || $workspaceId <= 0) {
            return null;
        }

        $backupHealth = app(TenantBackupHealthResolver::class)->assess($tenant);
        $recoveryEvidence = app(RestoreSafetyResolver::class)->dashboardRecoveryEvidence($tenant);

        $rows = app(ManagedEnvironmentTriageReviewStateResolver::class)->resolveMany(
            workspaceId: $workspaceId,
            tenantIds: [$tenantId],
            backupHealthByTenant: [$tenantId => $backupHealth],
            recoveryEvidenceByTenant: [$tenantId => $recoveryEvidence],
        )['rows'][$tenantId] ?? null;

        if (! is_array($rows)) {
            return null;
        }

        return static::selectedTriageReviewRow($rows, $triageState);
    }

    private static function applySnapshotTenantSubsetFilter(
        Builder $query,
        array $selectedValues,
        string $snapshotKey,
    ): Builder {
        if ($selectedValues === []) {
            return $query;
        }

        $snapshot = static::postureSnapshot();
        $tenantIds = collect($selectedValues)
            ->flatMap(static fn (string $value): array => $snapshot[$snapshotKey][$value] ?? [])
            ->map(static fn (mixed $tenantId): int => (int) $tenantId)
            ->unique()
            ->values()
            ->all();

        if ($tenantIds === []) {
            return $query->whereRaw('1 = 0');
        }

        return $query->whereIn((new ManagedEnvironment)->qualifyColumn('id'), $tenantIds);
    }

    private static function applyRecoveryEvidenceFilter(Builder $query, array $selectedValues): Builder
    {
        if ($selectedValues === []) {
            return $query;
        }

        $tenantIds = collect(static::postureSnapshot()['recovery_evidence'])
            ->filter(static fn (array $evidence): bool => in_array(
                TenantRecoveryTriagePresentation::recoveryEvidenceState($evidence),
                $selectedValues,
                true,
            ))
            ->keys()
            ->map(static fn (mixed $tenantId): int => (int) $tenantId)
            ->values()
            ->all();

        if ($tenantIds === []) {
            return $query->whereRaw('1 = 0');
        }

        return $query->whereIn((new ManagedEnvironment)->qualifyColumn('id'), $tenantIds);
    }

    /**
     * @param  list<string>  $selectedValues
     * @param  array{
     *     backup_posture?: list<string>,
     *     recovery_evidence?: list<string>,
     *     review_state?: list<string>,
     *     triage_sort?: string|null
     * }  $triageState
     */
    private static function applyReviewStateFilter(Builder $query, array $selectedValues, array $triageState): Builder
    {
        if ($selectedValues === []) {
            return $query;
        }

        $tenantIds = collect(static::triageReviewSnapshot()['rows'])
            ->map(function (mixed $rows, mixed $tenantId) use ($selectedValues, $triageState): ?int {
                if (! is_array($rows)) {
                    return null;
                }

                $row = static::selectedTriageReviewRow($rows, $triageState);

                if ($row === null) {
                    return null;
                }

                return in_array((string) ($row['derived_state'] ?? ''), $selectedValues, true)
                    ? (int) $tenantId
                    : null;
            })
            ->filter(static fn (?int $tenantId): bool => is_int($tenantId))
            ->values()
            ->all();

        if ($tenantIds === []) {
            return $query->whereRaw('1 = 0');
        }

        return $query->whereIn((new ManagedEnvironment)->qualifyColumn('id'), $tenantIds);
    }

    private static function applyWorstFirstTriageOrdering(Builder $query): Builder
    {
        $tiers = static::postureSnapshot()['triage_tiers'];

        if ($tiers === []) {
            return $query;
        }

        $qualifiedId = (new ManagedEnvironment)->qualifyColumn('id');
        $qualifiedName = (new ManagedEnvironment)->qualifyColumn('name');
        $clauses = [];
        $bindings = [];

        foreach ([1, 2, 3, 4, 5] as $tier) {
            $tenantIds = array_keys(array_filter($tiers, static fn (int $value): bool => $value === $tier));

            if ($tenantIds === []) {
                continue;
            }

            $placeholders = implode(', ', array_fill(0, count($tenantIds), '?'));
            $clauses[] = "when {$qualifiedId} in ({$placeholders}) then {$tier}";
            array_push($bindings, ...$tenantIds);
        }

        if ($clauses === []) {
            return $query->orderBy($qualifiedName);
        }

        return $query
            ->orderByRaw('case '.implode(' ', $clauses).' else 6 end', $bindings)
            ->orderBy($qualifiedName);
    }

    /**
     * @return array{
     *     tenant_ids: list<int>,
     *     backup_health: array<int, TenantBackupHealthAssessment>,
     *     recovery_evidence: array<int, array<string, mixed>>,
     *     backup_posture_ids: array<string, list<int>>,
     *     recovery_evidence_ids: array<string, list<int>>,
     *     triage_tiers: array<int, int>
     * }
     */
    private static function postureSnapshot(): array
    {
        $request = request();
        $snapshot = $request->attributes->get(self::POSTURE_SNAPSHOT_REQUEST_KEY);

        if (is_array($snapshot)) {
            return $snapshot;
        }

        $snapshot = static::buildPostureSnapshot();
        $request->attributes->set(self::POSTURE_SNAPSHOT_REQUEST_KEY, $snapshot);

        return $snapshot;
    }

    /**
     * @return array{
     *     tenant_ids: list<int>,
     *     backup_health: array<int, TenantBackupHealthAssessment>,
     *     recovery_evidence: array<int, array<string, mixed>>,
     *     backup_posture_ids: array<string, list<int>>,
     *     recovery_evidence_ids: array<string, list<int>>,
     *     triage_tiers: array<int, int>
     * }
     */
    private static function buildPostureSnapshot(): array
    {
        $tenantIds = static::visibleTenantIdsForPostureSnapshot();

        if ($tenantIds === []) {
            return [
                'tenant_ids' => [],
                'backup_health' => [],
                'recovery_evidence' => [],
                'backup_posture_ids' => [],
                'recovery_evidence_ids' => [],
                'triage_tiers' => [],
            ];
        }

        /** @var TenantBackupHealthResolver $backupHealthResolver */
        $backupHealthResolver = app(TenantBackupHealthResolver::class);
        $backupHealth = $backupHealthResolver->assessMany($tenantIds);

        /** @var RestoreSafetyResolver $restoreSafetyResolver */
        $restoreSafetyResolver = app(RestoreSafetyResolver::class);
        $recoveryEvidence = $restoreSafetyResolver->dashboardRecoveryEvidenceForTenants($tenantIds, $backupHealth);

        $triageTiers = [];

        foreach ($tenantIds as $tenantId) {
            $triageTiers[$tenantId] = TenantRecoveryTriagePresentation::triageTier(
                $backupHealth[$tenantId] ?? null,
                $recoveryEvidence[$tenantId] ?? null,
            );
        }

        return [
            'tenant_ids' => $tenantIds,
            'backup_health' => $backupHealth,
            'recovery_evidence' => $recoveryEvidence,
            'backup_posture_ids' => static::snapshotTenantIdsByBackupPosture($backupHealth),
            'recovery_evidence_ids' => static::snapshotTenantIdsByRecoveryEvidence($recoveryEvidence),
            'triage_tiers' => $triageTiers,
        ];
    }

    /**
     * @return list<int>
     */
    private static function visibleTenantIdsForPostureSnapshot(): array
    {
        /** @var Builder $query */
        $query = clone static::getEloquentQuery();

        return $query
            ->reorder()
            ->orderBy((new ManagedEnvironment)->qualifyColumn('name'))
            ->orderBy((new ManagedEnvironment)->qualifyColumn('id'))
            ->pluck((new ManagedEnvironment)->qualifyColumn('id'))
            ->map(static fn (mixed $tenantId): int => (int) $tenantId)
            ->all();
    }

    /**
     * @param  array<int, TenantBackupHealthAssessment>  $assessments
     * @return array<string, list<int>>
     */
    private static function snapshotTenantIdsByBackupPosture(array $assessments): array
    {
        $tenantIdsByPosture = [];

        foreach ($assessments as $tenantId => $assessment) {
            $tenantIdsByPosture[$assessment->posture] ??= [];
            $tenantIdsByPosture[$assessment->posture][] = (int) $tenantId;
        }

        return $tenantIdsByPosture;
    }

    /**
     * @param  array<int, array<string, mixed>>  $recoveryEvidence
     * @return array<string, list<int>>
     */
    private static function snapshotTenantIdsByRecoveryEvidence(array $recoveryEvidence): array
    {
        $tenantIdsByState = [];

        foreach ($recoveryEvidence as $tenantId => $evidence) {
            $state = TenantRecoveryTriagePresentation::recoveryEvidenceState($evidence);

            if ($state === null) {
                continue;
            }

            $tenantIdsByState[$state] ??= [];
            $tenantIdsByState[$state][] = (int) $tenantId;
        }

        return $tenantIdsByState;
    }

    public static function infolist(Schema $schema): Schema
    {
        // ... [Infolist Omitted - No Change] ...
        return $schema
            ->schema([
                Section::make('Identity')
                    ->schema([
                        Infolists\Components\TextEntry::make('name'),
                        Infolists\Components\TextEntry::make('managed_environment_id')->label('ManagedEnvironment ID')->copyable(),
                        Infolists\Components\TextEntry::make('domain')->copyable(),
                        Infolists\Components\TextEntry::make('status')
                            ->badge()
                            ->formatStateUsing(BadgeRenderer::label(BadgeDomain::TenantStatus))
                            ->color(BadgeRenderer::color(BadgeDomain::TenantStatus))
                            ->icon(BadgeRenderer::icon(BadgeDomain::TenantStatus))
                            ->iconColor(BadgeRenderer::iconColor(BadgeDomain::TenantStatus)),
                        Infolists\Components\TextEntry::make('workspace_posture')
                            ->label('Workspace posture')
                            ->badge()
                            ->state(fn (ManagedEnvironment $record): string => app(WorkspaceLifecycleService::class)->tenantPosture($record))
                            ->formatStateUsing(BadgeRenderer::label(BadgeDomain::TenantWorkspacePosture))
                            ->color(BadgeRenderer::color(BadgeDomain::TenantWorkspacePosture))
                            ->icon(BadgeRenderer::icon(BadgeDomain::TenantWorkspacePosture))
                            ->iconColor(BadgeRenderer::iconColor(BadgeDomain::TenantWorkspacePosture)),
                        Infolists\Components\TextEntry::make('lifecycle_summary')
                            ->label('Lifecycle summary')
                            ->state(fn (ManagedEnvironment $record): string => $record->isRemovedFromWorkspace()
                                ? 'Removed from workspace. The tenant is hidden from active context and new tenant operations, while historical evidence and operations remain available.'
                                : static::tenantLifecyclePresentation($record)->longDescription)
                            ->columnSpanFull(),
                    ])
                    ->columns(2)
                    ->columnSpanFull(),
                Section::make('Related context')
                    ->schema([
                        Infolists\Components\ViewEntry::make('related_context')
                            ->label('')
                            ->view('filament.infolists.entries.related-context')
                            ->state(fn (ManagedEnvironment $record): array => static::tenantViewContextEntries($record))
                            ->columnSpanFull(),
                    ])
                    ->columnSpanFull()
                    ->visible(fn (ManagedEnvironment $record): bool => static::tenantViewContextEntries($record) !== []),
                Section::make('Provider')
                    ->schema([
                        Infolists\Components\ViewEntry::make('provider_connection_state')
                            ->label('Provider connection')
                            ->state(fn (ManagedEnvironment $record): array => static::providerConnectionState($record))
                            ->view('filament.infolists.entries.provider-connection-state')
                            ->columnSpanFull(),
                    ])
                    ->columnSpanFull(),
                Section::make('RBAC')
                    ->schema([
                        Infolists\Components\TextEntry::make('rbac_not_configured_hint')
                            ->label('Status')
                            ->state('Not configured — Intune RBAC has not been set up for this tenant. Write operations will be blocked.')
                            ->icon('heroicon-o-shield-exclamation')
                            ->color('warning')
                            ->columnSpanFull()
                            ->visible(fn (ManagedEnvironment $record): bool => blank($record->rbac_status)),
                        Infolists\Components\TextEntry::make('rbac_status')
                            ->label('RBAC status')
                            ->badge()
                            ->formatStateUsing(BadgeRenderer::label(BadgeDomain::TenantRbacStatus))
                            ->color(BadgeRenderer::color(BadgeDomain::TenantRbacStatus))
                            ->icon(BadgeRenderer::icon(BadgeDomain::TenantRbacStatus))
                            ->iconColor(BadgeRenderer::iconColor(BadgeDomain::TenantRbacStatus))
                            ->visible(fn (ManagedEnvironment $record): bool => filled($record->rbac_status)),
                        Infolists\Components\TextEntry::make('rbac_explanation')
                            ->label('Summary')
                            ->state(function (ManagedEnvironment $record): string {
                                $status = $record->rbac_status;
                                $lastChecked = $record->rbac_last_checked_at;
                                $threshold = (int) config('tenantpilot.hardening.intune_write_gate.freshness_threshold_hours', 24);

                                if (blank($status) || $status === 'not_configured') {
                                    return 'RBAC is not configured. Write operations to this tenant are blocked until RBAC is set up.';
                                }

                                if (in_array($status, ['degraded', 'failed', 'error', 'missing', 'partial'], true)) {
                                    return 'RBAC health check reported an unhealthy state. Write operations are blocked.';
                                }

                                if ($status === 'ok' && ($lastChecked === null || $lastChecked->diffInHours(now()) >= $threshold)) {
                                    return "RBAC status is OK but the last health check is older than {$threshold} hours. Write operations are blocked until refreshed.";
                                }

                                return 'RBAC is healthy and up to date. Write operations are permitted.';
                            })
                            ->columnSpanFull()
                            ->visible(fn (ManagedEnvironment $record): bool => filled($record->rbac_status)),
                        Infolists\Components\TextEntry::make('rbac_last_checked_at')
                            ->label('Last checked')
                            ->since()
                            ->visible(fn (ManagedEnvironment $record): bool => filled($record->rbac_status)),
                        Infolists\Components\TextEntry::make('rbac_role_display_name')
                            ->label('RBAC role')
                            ->visible(fn (ManagedEnvironment $record): bool => filled($record->rbac_status)),
                        Section::make('RBAC Details')
                            ->schema([
                                Infolists\Components\TextEntry::make('rbac_status_reason_label')
                                    ->label('Reason')
                                    ->state(fn (ManagedEnvironment $record): ?string => app(\App\Support\ReasonTranslation\ReasonPresenter::class)
                                        ->primaryLabel(app(\App\Support\ReasonTranslation\ReasonPresenter::class)->forRbacReason($record->rbac_status_reason, 'detail')))
                                    ->visible(fn (?string $state): bool => filled($state)),
                                Infolists\Components\TextEntry::make('rbac_status_reason_explanation')
                                    ->label('Explanation')
                                    ->state(fn (ManagedEnvironment $record): ?string => app(\App\Support\ReasonTranslation\ReasonPresenter::class)
                                        ->shortExplanation(app(\App\Support\ReasonTranslation\ReasonPresenter::class)->forRbacReason($record->rbac_status_reason, 'detail')))
                                    ->visible(fn (?string $state): bool => filled($state))
                                    ->columnSpanFull(),
                                Infolists\Components\TextEntry::make('rbac_status_reason')
                                    ->label('Diagnostic code')
                                    ->copyable(),
                                Infolists\Components\TextEntry::make('rbac_role_definition_id')
                                    ->label('Role definition ID')
                                    ->copyable(),
                                Infolists\Components\TextEntry::make('rbac_scope_mode')
                                    ->label('Scope'),
                                Infolists\Components\TextEntry::make('rbac_scope_id')
                                    ->label('Scope ID'),
                                Infolists\Components\TextEntry::make('rbac_group_id')
                                    ->label('Group ID')
                                    ->copyable(),
                                Infolists\Components\TextEntry::make('rbac_role_assignment_id')
                                    ->label('Role assignment ID')
                                    ->copyable(),
                                Infolists\Components\ViewEntry::make('rbac_summary')
                                    ->label('Last RBAC Setup')
                                    ->view('filament.infolists.entries.rbac-summary')
                                    ->visible(fn (ManagedEnvironment $record) => filled($record->rbac_last_setup_at)),
                            ])
                            ->columns(2)
                            ->collapsible()
                            ->collapsed()
                            ->visible(fn (ManagedEnvironment $record): bool => filled($record->rbac_status)),
                    ])
                    ->columns(2)
                    ->columnSpanFull()
                    ->collapsible(),
                Section::make('Integration')
                    ->schema([
                        Infolists\Components\TextEntry::make('admin_consent_url')
                            ->label('Grant admin consent URL')
                            ->state(fn (ManagedEnvironment $record) => static::adminConsentUrl($record))
                            ->visible(fn (?string $state) => filled($state))
                            ->copyable()
                            ->columnSpanFull(),
                    ])
                    ->columnSpanFull()
                    ->collapsible(),
                Section::make('Metadata')
                    ->schema([
                        Infolists\Components\TextEntry::make('created_at')->dateTime(),
                        Infolists\Components\TextEntry::make('updated_at')->dateTime(),
                    ])
                    ->columns(2)
                    ->columnSpanFull()
                    ->collapsed(),
                Section::make('Required permissions')
                    ->schema([
                        Infolists\Components\RepeatableEntry::make('permissions')
                            ->label('')
                            ->state(fn (ManagedEnvironment $record) => static::storedPermissionSnapshot($record))
                            ->schema([
                                Infolists\Components\TextEntry::make('key')->label('Permission')->badge(),
                                Infolists\Components\TextEntry::make('type')->badge(),
                                Infolists\Components\TextEntry::make('features')
                                    ->label('Features')
                                    ->formatStateUsing(fn ($state) => is_array($state) ? implode(', ', $state) : (string) $state),
                                Infolists\Components\TextEntry::make('status')
                                    ->badge()
                                    ->formatStateUsing(BadgeRenderer::label(BadgeDomain::ManagedEnvironmentPermissionStatus))
                                    ->color(BadgeRenderer::color(BadgeDomain::ManagedEnvironmentPermissionStatus))
                                    ->icon(BadgeRenderer::icon(BadgeDomain::ManagedEnvironmentPermissionStatus))
                                    ->iconColor(BadgeRenderer::iconColor(BadgeDomain::ManagedEnvironmentPermissionStatus)),
                            ])
                            ->columnSpanFull(),
                    ])
                    ->columnSpanFull()
                    ->collapsible(),
            ]);
    }

    /**
     * @return array<int, array{key:string,type:string,description:?string,features:array<int,string>,status:string,details:array<string,mixed>|null}>
     */
    protected static function storedPermissionSnapshot(ManagedEnvironment $tenant): array
    {
        $required = config('intune_permissions.permissions', []);

        $stored = $tenant->permissions()
            ->get()
            ->keyBy('permission_key');

        $snapshot = [];

        foreach ($required as $permission) {
            $key = is_string($permission['key'] ?? null) ? (string) $permission['key'] : null;

            if ($key === null || $key === '') {
                continue;
            }

            $storedEntry = $stored->get($key);
            $storedDetails = $storedEntry?->details;

            $snapshot[] = [
                'key' => $key,
                'type' => is_string($permission['type'] ?? null) ? (string) $permission['type'] : 'application',
                'description' => is_string($permission['description'] ?? null) ? (string) $permission['description'] : null,
                'features' => is_array($permission['features'] ?? null) ? $permission['features'] : [],
                'status' => is_string($storedEntry?->status ?? null) ? (string) $storedEntry->status : 'missing',
                'details' => is_array($storedDetails) ? $storedDetails : null,
            ];
        }

        return $snapshot;
    }

    protected static function tenantLifecyclePresentation(ManagedEnvironment $tenant): TenantLifecyclePresentation
    {
        return TenantLifecyclePresentation::fromTenant($tenant);
    }

    public static function tenantOperability(): TenantOperabilityService
    {
        return app(TenantOperabilityService::class);
    }

    public static function tenantActionPolicy(): TenantActionPolicySurface
    {
        return app(TenantActionPolicySurface::class);
    }

    /**
     * @return Collection<int, TenantActionDescriptor>
     */
    public static function tenantActionCatalog(ManagedEnvironment $tenant, TenantActionSurface $surface = TenantActionSurface::TenantIndexRow): Collection
    {
        $cacheKey = static::tenantActionCatalogCacheKey($tenant, $surface);

        if (! array_key_exists($cacheKey, static::$tenantActionCatalogCache)) {
            static::$tenantActionCatalogCache[$cacheKey] = collect(static::tenantActionPolicy()->catalogForTenant($tenant, $surface))->values();
        }

        return static::$tenantActionCatalogCache[$cacheKey];
    }

    public static function lifecycleActionDescriptor(ManagedEnvironment $tenant, TenantActionSurface $surface = TenantActionSurface::TenantIndexRow): ?TenantActionDescriptor
    {
        return static::tenantActionDescriptorForSurface($tenant, $surface, 'restore')
            ?? static::tenantActionDescriptorForSurface($tenant, $surface, 'archive');
    }

    public static function tenantIndexPrimaryAction(ManagedEnvironment $tenant): ?TenantActionDescriptor
    {
        $catalog = static::tenantActionCatalog($tenant, TenantActionSurface::TenantIndexRow);

        return $catalog[1] ?? null;
    }

    public static function relatedOnboardingDraft(ManagedEnvironment $tenant): ?ManagedEnvironmentOnboardingSession
    {
        return static::tenantActionPolicy()->relatedOnboardingDraft($tenant);
    }

    public static function relatedOnboardingDraftAction(ManagedEnvironment $tenant, TenantActionSurface $surface = TenantActionSurface::TenantViewHeader): ?TenantActionDescriptor
    {
        return static::tenantActionDescriptorForSurface($tenant, $surface, 'related_onboarding');
    }

    public static function relatedOnboardingDraftActionLabel(ManagedEnvironment $tenant, TenantActionSurface $surface = TenantActionSurface::TenantViewHeader): ?string
    {
        return static::relatedOnboardingDraftAction($tenant, $surface)?->label;
    }

    public static function relatedOnboardingDraftUrl(ManagedEnvironment $tenant): ?string
    {
        $draft = static::relatedOnboardingDraft($tenant);

        if (! $draft instanceof ManagedEnvironmentOnboardingSession) {
            return null;
        }

        return route('admin.onboarding.draft', ['onboardingDraft' => (int) $draft->getKey()]);
    }

    /**
     * @return array<int, array<string, mixed>>
     */
    public static function tenantViewContextEntries(ManagedEnvironment $tenant): array
    {
        $entries = [];

        if (static::canEdit($tenant)) {
            $entries[] = RelatedContextEntry::available(
                key: 'tenant_edit',
                label: 'ManagedEnvironment edit',
                value: 'Edit tenant',
                secondaryValue: 'Update tenant identity and lifecycle metadata.',
                targetUrl: static::getUrl('edit', ['record' => $tenant]),
                targetKind: 'direct_record',
                priority: 10,
                actionLabel: 'Edit',
                contextBadge: 'Management',
            );
        } elseif (static::viewerCanInspectTenantContext($tenant)) {
            $entries[] = RelatedContextEntry::unavailable(
                key: 'tenant_edit',
                label: 'ManagedEnvironment edit',
                state: new UnavailableRelationState(
                    relationKey: 'tenant_edit',
                    referenceValue: null,
                    reason: 'authorization_denied',
                    message: UiTooltips::insufficientPermission(),
                ),
                targetKind: 'direct_record',
                priority: 10,
                actionLabel: 'Edit',
            );
        }

        if (static::viewerHasTenantCapability($tenant, Capabilities::PROVIDER_VIEW)) {
            $entries[] = RelatedContextEntry::available(
                key: 'provider_connections',
                label: 'Provider connections',
                value: 'Open provider connections',
                secondaryValue: 'Inspect consent, credentials, and health for this tenant.',
                targetUrl: ManagedEnvironmentLinks::providerConnectionsUrl($tenant),
                targetKind: 'canonical_page',
                priority: 20,
                actionLabel: 'Open',
                contextBadge: 'Integrations',
            );
        } elseif (static::viewerCanInspectTenantContext($tenant)) {
            $entries[] = RelatedContextEntry::unavailable(
                key: 'provider_connections',
                label: 'Provider connections',
                state: new UnavailableRelationState(
                    relationKey: 'provider_connections',
                    referenceValue: null,
                    reason: 'authorization_denied',
                    message: UiTooltips::insufficientPermission(),
                ),
                targetKind: 'canonical_page',
                priority: 20,
                actionLabel: 'Open',
            );
        }

        $relatedOnboarding = static::relatedOnboardingDraftAction($tenant, TenantActionSurface::TenantViewHeader);

        if ($relatedOnboarding instanceof TenantActionDescriptor && filled(static::relatedOnboardingDraftUrl($tenant))) {
            $entries[] = RelatedContextEntry::available(
                key: 'related_onboarding',
                label: 'Onboarding draft',
                value: $relatedOnboarding->label,
                secondaryValue: 'Return to the linked onboarding workflow for this tenant.',
                targetUrl: (string) static::relatedOnboardingDraftUrl($tenant),
                targetKind: 'workflow',
                priority: 30,
                actionLabel: 'Open',
                contextBadge: 'Workflow',
            );
        }

        return collect($entries)
            ->sortBy('priority')
            ->values()
            ->map(static fn (RelatedContextEntry $entry): array => $entry->toArray())
            ->all();
    }

    /**
     * @return array<int, array<string, mixed>>
     */
    public static function tenantEditContextEntries(ManagedEnvironment $tenant): array
    {
        $entries = [
            RelatedContextEntry::available(
                key: 'tenant_view',
                label: 'ManagedEnvironment detail',
                value: 'Open environment detail',
                secondaryValue: 'Review verification, RBAC, and lifecycle context without leaving the tenant resource.',
                targetUrl: static::getUrl('view', ['record' => $tenant]),
                targetKind: 'direct_record',
                priority: 10,
                actionLabel: 'Open',
                contextBadge: 'Inspection',
            ),
        ];

        $relatedOnboarding = static::relatedOnboardingDraftAction($tenant, TenantActionSurface::TenantEditHeader);

        if ($relatedOnboarding instanceof TenantActionDescriptor && filled(static::relatedOnboardingDraftUrl($tenant))) {
            $entries[] = RelatedContextEntry::available(
                key: 'related_onboarding',
                label: 'Onboarding draft',
                value: $relatedOnboarding->label,
                secondaryValue: 'Return to the linked onboarding workflow for this tenant.',
                targetUrl: (string) static::relatedOnboardingDraftUrl($tenant),
                targetKind: 'workflow',
                priority: 20,
                actionLabel: 'Open',
                contextBadge: 'Workflow',
            );
        }

        return collect($entries)
            ->sortBy('priority')
            ->values()
            ->map(static fn (RelatedContextEntry $entry): array => $entry->toArray())
            ->all();
    }

    public static function tenantEditContextHtml(?ManagedEnvironment $tenant): HtmlString
    {
        if (! $tenant instanceof ManagedEnvironment) {
            return new HtmlString('');
        }

        $entries = static::tenantEditContextEntries($tenant);

        if ($entries === []) {
            return new HtmlString('');
        }

        return new HtmlString((string) view('filament.infolists.entries.related-context', [
            'entries' => $entries,
        ])->render());
    }

    public static function tenantViewLifecycleGroupVisible(ManagedEnvironment $tenant): bool
    {
        return in_array(static::lifecycleActionDescriptor($tenant, TenantActionSurface::TenantViewHeader)?->key, ['archive', 'restore'], true)
            || static::tenantWorkspaceRemovalActionVisible($tenant)
            || static::tenantWorkspaceRestoreActionVisible($tenant);
    }

    public static function tenantViewExternalGroupVisible(ManagedEnvironment $tenant): bool
    {
        return static::adminConsentUrl($tenant) !== null || static::entraUrl($tenant) !== null;
    }

    public static function tenantViewSetupGroupVisible(ManagedEnvironment $tenant): bool
    {
        return static::tenantSetupMutationVisible($tenant);
    }

    public static function tenantSetupMutationVisible(ManagedEnvironment $tenant): bool
    {
        return $tenant->isActive()
            && ! $tenant->isRemovedFromWorkspace()
            && ! $tenant->workspace?->isClosed();
    }

    public static function tenantWorkspaceRemovalActionVisible(ManagedEnvironment $tenant): bool
    {
        return ! $tenant->trashed() && ! $tenant->isRemovedFromWorkspace();
    }

    public static function tenantWorkspaceRestoreActionVisible(ManagedEnvironment $tenant): bool
    {
        return $tenant->isRemovedFromWorkspace();
    }

    public static function verificationActionVisible(ManagedEnvironment $tenant): bool
    {
        $outcome = static::verificationReadinessOutcome($tenant);

        return $outcome->allowed || $outcome->isDeniedForCapability();
    }

    public static function verificationReadinessOutcome(ManagedEnvironment $tenant): TenantOperabilityOutcome
    {
        $user = auth()->user();

        return static::tenantOperability()->outcomeFor(
            tenant: $tenant,
            question: TenantOperabilityQuestion::VerificationReadinessEligibility,
            actor: $user instanceof User ? $user : null,
            workspaceId: app(WorkspaceContext::class)->currentWorkspaceId(request()),
            lane: TenantInteractionLane::AdministrativeManagement,
        );
    }

    private static function tenantActionDescriptorForSurface(ManagedEnvironment $tenant, TenantActionSurface $surface, string $key): ?TenantActionDescriptor
    {
        $descriptor = static::tenantActionCatalog($tenant, $surface)
            ->first(fn (TenantActionDescriptor $descriptor): bool => $descriptor->key === $key);

        return $descriptor instanceof TenantActionDescriptor ? $descriptor : null;
    }

    private static function tenantActionCatalogCacheKey(ManagedEnvironment $tenant, TenantActionSurface $surface): string
    {
        $relatedDraft = static::relatedOnboardingDraft($tenant);

        return implode(':', [
            (string) (auth()->id() ?? 'guest'),
            $surface->value,
            (string) ($tenant->getKey() ?? 'missing'),
            (string) $tenant->status,
            (string) ($tenant->removed_from_workspace_at?->getTimestamp() ?? 'not-removed-from-workspace'),
            (string) ($tenant->updated_at?->getTimestamp() ?? 'no-updated-at'),
            (string) ($tenant->deleted_at?->getTimestamp() ?? 'not-deleted'),
            (string) ($relatedDraft?->getKey() ?? 'no-draft'),
            (string) ($relatedDraft?->workflowStatus()->value ?? 'no-draft-status'),
            (string) ($relatedDraft?->lifecycleState()->value ?? 'no-draft-lifecycle-state'),
            (string) ($relatedDraft?->updated_at?->getTimestamp() ?? 'no-draft-updated-at'),
            (string) ($relatedDraft?->completed_at?->getTimestamp() ?? 'no-draft-completed-at'),
            (string) ($relatedDraft?->cancelled_at?->getTimestamp() ?? 'no-draft-cancelled-at'),
        ]);
    }

    private static function viewerCanInspectTenantContext(ManagedEnvironment $tenant): bool
    {
        $user = auth()->user();

        return $user instanceof User && $user->canAccessTenant($tenant);
    }

    private static function viewerHasTenantCapability(ManagedEnvironment $tenant, string $capability): bool
    {
        $user = auth()->user();

        if (! $user instanceof User || ! $user->canAccessTenant($tenant)) {
            return false;
        }

        /** @var CapabilityResolver $resolver */
        $resolver = app(CapabilityResolver::class);

        return $resolver->isMember($user, $tenant)
            && $resolver->can($user, $tenant, $capability);
    }

    public static function archiveTenant(ManagedEnvironment $record, WorkspaceAuditLogger $auditLogger, string $reason): void
    {
        $user = auth()->user();
        $reason = static::validatedLifecycleReason($reason, 'archive_reason');

        if (! $user instanceof User) {
            abort(403);
        }

        if (! $user->canAccessTenant($record)) {
            abort(404);
        }

        /** @var CapabilityResolver $resolver */
        $resolver = app(CapabilityResolver::class);

        if (! $resolver->can($user, $record, Capabilities::TENANT_DELETE)) {
            abort(403);
        }

        $descriptor = static::lifecycleActionDescriptor($record);

        if (! $descriptor instanceof TenantActionDescriptor || $descriptor->key !== 'archive') {
            Notification::make()
                ->title('Archive unavailable')
                ->body('Only active tenants can be archived from tenant management surfaces.')
                ->warning()
                ->send();

            return;
        }

        $record->delete();

        $auditLogger->logTenantLifecycleAction(
            tenant: $record,
            action: AuditActionId::TenantArchived,
            actor: $user,
            context: ['metadata' => ['managed_environment_id' => $record->managed_environment_id, 'reason' => $reason]]
        );

        Notification::make()
            ->title(GovernanceActionCatalog::rule('archive_tenant')->successTitle)
            ->body($descriptor->successNotificationBody ?? 'The tenant remains available for inspection and audit history, but it is no longer selectable as active context.')
            ->success()
            ->send();
    }

    public static function restoreTenant(ManagedEnvironment $record, WorkspaceAuditLogger $auditLogger): void
    {
        $user = auth()->user();

        if (! $user instanceof User) {
            abort(403);
        }

        if (! $user->canAccessTenant($record)) {
            abort(404);
        }

        /** @var CapabilityResolver $resolver */
        $resolver = app(CapabilityResolver::class);

        if (! $resolver->can($user, $record, Capabilities::TENANT_DELETE)) {
            abort(403);
        }

        $descriptor = static::lifecycleActionDescriptor($record);

        if (! $descriptor instanceof TenantActionDescriptor || $descriptor->key !== 'restore') {
            Notification::make()
                ->title('Restore unavailable')
                ->body('Only archived tenants can be restored from tenant management surfaces.')
                ->warning()
                ->send();

            return;
        }

        $record->restore();

        $auditLogger->logTenantLifecycleAction(
            tenant: $record,
            action: AuditActionId::TenantRestored,
            actor: $user,
            context: ['metadata' => ['managed_environment_id' => $record->managed_environment_id]]
        );

        Notification::make()
            ->title(GovernanceActionCatalog::rule('restore_tenant')->successTitle)
            ->body($descriptor->successNotificationBody ?? 'The tenant is available again in normal tenant management flows and can be selected as active context.')
            ->success()
            ->send();
    }

    private static function validatedLifecycleReason(string $reason, string $field): string
    {
        $reason = trim($reason);

        if ($reason === '') {
            throw new \InvalidArgumentException(sprintf('%s is required.', $field));
        }

        if (mb_strlen($reason) > 2000) {
            throw new \InvalidArgumentException(sprintf('%s must be at most 2000 characters.', $field));
        }

        return $reason;
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListManagedEnvironments::route('/'),
            'view' => Pages\ViewManagedEnvironment::route('/{record}'),
            'edit' => Pages\EditManagedEnvironment::route('/{record}/edit'),
            'memberships' => Pages\ManageEnvironmentAccessScopes::route('/{record}/memberships'),
        ];
    }

    public static function getRelations(): array
    {
        return [
            RelationManagers\ManagedEnvironmentMembershipsRelationManager::class,
        ];
    }

    /**
     * @param  array<mixed>  $parameters
     */
    public static function getUrl(?string $name = null, array $parameters = [], bool $isAbsolute = true, ?string $panel = null, ?Model $tenant = null, bool $shouldGuessMissingParameters = false): string
    {
        $environment = static::resolveUrlEnvironment(
            $parameters['record']
                ?? $parameters['tenant']
                ?? $parameters['environment']
                ?? $tenant
                ?? null,
        );

        $query = $parameters;
        unset($query['record'], $query['tenant'], $query['environment'], $query['workspace']);

        if ($name === 'memberships' && $environment instanceof ManagedEnvironment) {
            return ManagedEnvironmentLinks::accessScopesUrl($environment, $query);
        }

        if (($name === 'view' || $name === 'edit') && $environment instanceof ManagedEnvironment) {
            return ManagedEnvironmentLinks::viewUrl($environment, $query);
        }

        if ($name === null || $name === 'index') {
            $scope = $environment ?? ($parameters['workspace'] ?? null);

            return ManagedEnvironmentLinks::indexUrl($scope instanceof Workspace || $scope instanceof ManagedEnvironment ? $scope : null, $query);
        }

        if ($environment instanceof ManagedEnvironment) {
            return ManagedEnvironmentLinks::viewUrl($environment, $query);
        }

        return ManagedEnvironmentLinks::indexUrl(query: $query);
    }

    private static function resolveUrlEnvironment(mixed $environment): ?ManagedEnvironment
    {
        if ($environment instanceof ManagedEnvironment) {
            return $environment;
        }

        if ($environment instanceof Model) {
            return null;
        }

        $identifier = trim((string) $environment);

        if ($identifier === '') {
            return null;
        }

        return ManagedEnvironment::query()
            ->withTrashed()
            ->where(static function (Builder $query) use ($identifier): void {
                $query->where('slug', $identifier);

                if (ctype_digit($identifier)) {
                    $query->orWhere((new ManagedEnvironment)->getQualifiedKeyName(), (int) $identifier);
                }
            })
            ->first();
    }

    public static function rbacAction(): Actions\Action
    {
        // ... [RBAC Action Omitted - No Change] ...
        return Actions\Action::make('setup_rbac')
            ->label('Setup Intune RBAC')
            ->icon('heroicon-o-shield-check')
            ->color('primary')
            ->form([
                Forms\Components\Select::make('role_definition_id')
                    ->label('RBAC role')
                    ->required()
                    ->searchable()
                    ->optionsLimit(20)
                    ->searchDebounce(400)
                    ->getSearchResultsUsing(fn (string $search, ?ManagedEnvironment $record) => static::roleSearchOptions($record, $search))
                    ->getOptionLabelUsing(fn (?string $value, ?ManagedEnvironment $record) => static::roleLabelFromCache($record, $value))
                    ->helperText(fn (?ManagedEnvironment $record) => static::roleSearchHelper($record))
                    ->hintAction(fn (?ManagedEnvironment $record) => static::syncRoleDefinitionsAction())
                    ->hint('Wizard grants Intune RBAC roles only. "Intune Administrator" is an Entra directory role and is not assigned here.')
                    ->noSearchResultsMessage('No Intune RBAC roleDefinitions found (tenant may restrict RBAC or missing permission).')
                    ->loadingMessage('Loading roles...')
                    ->afterStateUpdated(function (Set $set, ?string $state, ?ManagedEnvironment $record) {
                        $set('role_display_name', static::roleNameFromCache($record, $state));
                    }),
                Forms\Components\Hidden::make('role_display_name')
                    ->dehydrated(),
                Forms\Components\Select::make('scope')
                    ->label('Scope')
                    ->required()
                    ->options([
                        'all_devices' => 'All devices (global)',
                        'scope_group' => 'Scope group (enter ID)',
                    ])
                    ->default('all_devices')
                    ->live(),
                Forms\Components\Select::make('scope_group_id')
                    ->label('Scope group')
                    ->searchable()
                    ->searchPrompt('Type at least 2 characters')
                    ->optionsLimit(20)
                    ->searchDebounce(400)
                    ->placeholder('Search security groups')
                    ->visible(fn (Get $get) => $get('scope') === 'scope_group')
                    ->required(fn (Get $get) => $get('scope') === 'scope_group')
                    ->disabled(fn (?ManagedEnvironment $record): bool => static::delegatedToken($record) === null)
                    ->getSearchResultsUsing(fn (string $search, ?ManagedEnvironment $record) => static::groupSearchOptions($record, $search))
                    ->getOptionLabelUsing(fn (?string $value, ?ManagedEnvironment $record) => static::groupLabelFromCache($record, $value))
                    ->noSearchResultsMessage('No security groups found')
                    ->loadingMessage('Searching groups...'),
                Forms\Components\Select::make('group_mode')
                    ->label('Group mode')
                    ->required()
                    ->options([
                        'create' => 'Create new security group',
                        'existing' => 'Use existing security group',
                    ])
                    ->default('create')
                    ->live(),
                Forms\Components\TextInput::make('group_name')
                    ->label('Group name')
                    ->default('TenantPilot-Intune-RBAC')
                    ->visible(fn (callable $get) => $get('group_mode') === 'create'),
                Forms\Components\Select::make('existing_group_id')
                    ->label('Security group')
                    ->searchable()
                    ->searchPrompt('Type at least 2 characters')
                    ->optionsLimit(20)
                    ->searchDebounce(400)
                    ->placeholder('Search security groups')
                    ->visible(fn (Get $get) => $get('group_mode') === 'existing')
                    ->required(fn (Get $get) => $get('group_mode') === 'existing')
                    ->disabled(fn (?ManagedEnvironment $record): bool => static::delegatedToken($record) === null)
                    ->getSearchResultsUsing(fn (string $search, ?ManagedEnvironment $record) => static::groupSearchOptions($record, $search))
                    ->getOptionLabelUsing(fn (?string $value, ?ManagedEnvironment $record) => static::groupLabelFromCache($record, $value))
                    ->noSearchResultsMessage('No security groups found')
                    ->loadingMessage('Searching groups...'),
            ])
            ->visible(fn (ManagedEnvironment $record): bool => static::tenantSetupMutationVisible($record))
            ->disabled(function (ManagedEnvironment $record): bool {
                $user = auth()->user();

                if (! $user instanceof User) {
                    return true;
                }

                /** @var CapabilityResolver $resolver */
                $resolver = app(CapabilityResolver::class);

                return ! $resolver->can($user, $record, Capabilities::TENANT_MANAGE);
            })
            ->requiresConfirmation()
            ->action(function (
                array $data,
                ManagedEnvironment $record,
                RbacOnboardingService $service,
                AuditLogger $auditLogger
            ) {
                $user = auth()->user();

                if (! $user instanceof User) {
                    abort(403);
                }

                /** @var CapabilityResolver $resolver */
                $resolver = app(CapabilityResolver::class);

                if (! $resolver->can($user, $record, Capabilities::TENANT_MANAGE)) {
                    abort(403);
                }

                $userCacheKey = RbacDelegatedAuthController::cacheKey($record, auth()->id(), null);
                $sessionCacheKey = RbacDelegatedAuthController::cacheKey($record, auth()->id(), session()->getId());

                $token = Cache::get($sessionCacheKey) ?? Cache::get($userCacheKey);

                if (! $token) {
                    Notification::make()
                        ->title('Login to grant RBAC')
                        ->body('Delegated login required to continue.')
                        ->actions([
                            Actions\Action::make('open_rbac_login')
                                ->label('Open RBAC login')
                                ->url(route('admin.rbac.start', [
                                    'tenant' => $record->graphTenantId(),
                                    'return' => ManagedEnvironmentLinks::viewUrl($record),
                                ])),
                        ])
                        ->warning()
                        ->persistent()
                        ->send();

                    return;
                }

                $result = $service->run($record, $data, $user, $token);

                Cache::forget($sessionCacheKey);
                Cache::forget($userCacheKey);

                if ($result['status'] === 'success') {
                    Notification::make()
                        ->title('RBAC setup completed')
                        ->body(sprintf(
                            'Role: %s | Scope: %s | Group: %s | Assignment: %s',
                            $data['role_display_name'] ?? $data['role_definition_id'] ?? 'n/a',
                            $data['scope'] ?? 'n/a',
                            $result['group_id'] ?? 'n/a',
                            $result['role_assignment_id'] ?? 'n/a'
                        ))
                        ->success()
                        ->send();

                    if (($data['scope'] ?? null) === 'scope_group') {
                        Notification::make()
                            ->title('Scope-limited selection')
                            ->body('RBAC scope is limited to a scope group; inventory/restore may be partial.')
                            ->warning()
                            ->send();
                    }

                    if (config('tenantpilot.features.conditional_access', false) === false) {
                        Notification::make()
                            ->title('CA canary disabled')
                            ->body('Conditional Access canary is disabled by feature flag.')
                            ->warning()
                            ->send();
                    }

                    return;
                }

                $auditLogger->log(
                    tenant: $record,
                    action: 'rbac.setup.failed',
                    resourceType: 'tenant',
                    resourceId: (string) $record->id,
                    status: 'error',
                    context: ['metadata' => ['error' => $result['message'] ?? 'unknown']],
                );

                Notification::make()
                    ->title('RBAC setup failed')
                    ->body($result['message'] ?? 'Unknown error')
                    ->danger()
                    ->send();
            });
    }

    public static function adminConsentUrl(ManagedEnvironment $tenant): ?string
    {
        $connection = ProviderConnection::query()
            ->where('managed_environment_id', (int) $tenant->getKey())
            ->where('provider', 'microsoft')
            ->orderByDesc('is_default')
            ->orderBy('id')
            ->first();

        if (! $connection instanceof ProviderConnection) {
            return null;
        }

        try {
            return app(AdminConsentUrlFactory::class)->make($connection, sprintf('tenantpilot|%s', $tenant->id));
        } catch (\Throwable) {
            return null;
        }
    }

    /**
     * @return array{
     *   state:string,
     *   cta_url:string,
     *   lifecycle:?string,
     *   is_enabled:?bool,
     *   display_name:?string,
     *   provider:?string,
     *   consent_status:?string,
     *   verification_status:?string,
     *   last_health_check_at:?string,
     *   last_error_reason_code:?string,
     *   target_scope_summary:?string
     * }
     */
    private static function providerConnectionState(ManagedEnvironment $tenant): array
    {
        $ctaUrl = ManagedEnvironmentLinks::providerConnectionsUrl($tenant);

        $defaultConnection = ProviderConnection::query()
            ->where('managed_environment_id', (int) $tenant->getKey())
            ->where('provider', 'microsoft')
            ->where('is_default', true)
            ->orderBy('id')
            ->first();

        $connection = $defaultConnection instanceof ProviderConnection
            ? $defaultConnection
            : ProviderConnection::query()
                ->where('managed_environment_id', (int) $tenant->getKey())
                ->where('provider', 'microsoft')
                ->orderBy('id')
                ->first();

        if (! $connection instanceof ProviderConnection) {
            return [
                'state' => 'missing',
                'cta_url' => $ctaUrl,
                'needs_default_connection' => false,
                'display_name' => null,
                'provider' => null,
                'lifecycle' => null,
                'is_enabled' => null,
                'consent_status' => null,
                'verification_status' => null,
                'last_health_check_at' => null,
                'last_error_reason_code' => null,
                'target_scope_summary' => null,
            ];
        }

        try {
            $targetScopeSummary = ProviderConnectionSurfaceSummary::forConnection($connection)->targetScopeSummary();
        } catch (\InvalidArgumentException) {
            $targetScopeSummary = 'Target scope needs review';
        }

        return [
            'state' => $connection->is_default ? 'default_configured' : 'configured',
            'cta_url' => $ctaUrl,
            'needs_default_connection' => ! $connection->is_default,
            'display_name' => (string) $connection->display_name,
            'provider' => (string) $connection->provider,
            'lifecycle' => (bool) $connection->is_enabled ? 'enabled' : 'disabled',
            'is_enabled' => (bool) $connection->is_enabled,
            'consent_status' => $connection->consent_status instanceof BackedEnum
                ? (string) $connection->consent_status->value
                : (is_string($connection->consent_status) ? $connection->consent_status : null),
            'verification_status' => $connection->verification_status instanceof BackedEnum
                ? (string) $connection->verification_status->value
                : (is_string($connection->verification_status) ? $connection->verification_status : null),
            'last_health_check_at' => optional($connection->last_health_check_at)->toDateTimeString(),
            'last_error_reason_code' => is_string($connection->last_error_reason_code) ? $connection->last_error_reason_code : null,
            'target_scope_summary' => $targetScopeSummary,
        ];
    }

    public static function entraUrl(ManagedEnvironment $tenant): ?string
    {
        $connection = ProviderConnection::query()
            ->where('managed_environment_id', (int) $tenant->getKey())
            ->where('provider', 'microsoft')
            ->orderByDesc('is_default')
            ->orderBy('id')
            ->first();

        $effectiveAppId = $connection instanceof ProviderConnection
            ? $connection->effectiveAppId()
            : null;

        if (! filled($effectiveAppId)) {
            $effectiveAppId = $tenant->legacyProviderClientId();
        }

        if (filled($effectiveAppId)) {
            return sprintf(
                'https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/ApplicationMenuBlade/~/Overview/appId/%s',
                $effectiveAppId
            );
        }

        if ($tenant->graphTenantId()) {
            return sprintf(
                'https://entra.microsoft.com/#view/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/~/Overview/tenantId/%s',
                $tenant->graphTenantId()
            );
        }

        return null;
    }

    private static function delegatedToken(?ManagedEnvironment $tenant): ?string
    {
        if (! $tenant) {
            return null;
        }

        $userKey = RbacDelegatedAuthController::cacheKey($tenant, auth()->id(), null);
        $sessionKey = RbacDelegatedAuthController::cacheKey($tenant, auth()->id(), session()->getId());

        return Cache::get($userKey) ?? Cache::get($sessionKey);
    }

    private static function loginToSearchRolesAction(?ManagedEnvironment $tenant): ?Actions\Action
    {
        return null;
    }

    public static function roleSearchHelper(?ManagedEnvironment $tenant): ?string
    {
        if (! $tenant) {
            return null;
        }

        return static::delegatedToken($tenant) === null ? 'Login to search roles' : null;
    }

    /**
     * @return array<string, string>
     */
    public static function roleSearchOptions(?ManagedEnvironment $tenant, string $search): array
    {
        $token = static::delegatedToken($tenant);

        if ($token !== null) {
            return static::searchRoleDefinitionsDelegated($tenant, $search, $token);
        }

        return static::searchRoleDefinitions($tenant, $search);
    }

    /**
     * @return array<string, string>
     */
    private static function searchRoleDefinitionsDelegated(?ManagedEnvironment $tenant, string $search, string $token): array
    {
        if (! $tenant || mb_strlen($search) < 2) {
            return [];
        }

        $needle = mb_strtolower($search);

        /** @var GraphClientInterface $graph */
        $graph = app(GraphClientInterface::class);

        $response = $graph->request('GET', 'deviceManagement/roleDefinitions', [
            'access_token' => $token,
        ]);

        if ($response->failed()) {
            return [];
        }

        $roles = is_array($response->data['value'] ?? null) ? $response->data['value'] : [];

        $results = [];

        foreach ($roles as $role) {
            $id = is_string($role['id'] ?? null) ? (string) $role['id'] : null;
            $displayName = is_string($role['displayName'] ?? null) ? (string) $role['displayName'] : null;

            if (! $id || ! $displayName) {
                continue;
            }

            if (! str_contains(mb_strtolower($displayName), $needle)) {
                continue;
            }

            $results[$id] = static::formatRoleLabel($displayName, $id);
        }

        ksort($results);

        return array_slice($results, 0, 20, true);
    }

    /**
     * @return array<string, string>
     */
    private static function searchRoleDefinitions(?ManagedEnvironment $tenant, string $search): array
    {
        if (! $tenant || mb_strlen($search) < 2) {
            return [];
        }

        $needle = mb_strtolower($search);

        return EntraRoleDefinition::query()
            ->where('managed_environment_id', $tenant->getKey())
            ->whereRaw('lower(display_name) like ?', [$needle.'%'])
            ->orderBy('display_name')
            ->limit(20)
            ->get(['entra_id', 'display_name'])
            ->mapWithKeys(fn (EntraRoleDefinition $role): array => [
                (string) $role->entra_id => static::formatRoleLabel((string) $role->display_name, (string) $role->entra_id),
            ])
            ->all();
    }

    public static function roleLabelFromCache(?ManagedEnvironment $tenant, ?string $roleId): ?string
    {
        if (! $tenant || blank($roleId)) {
            return $roleId;
        }

        $displayName = EntraRoleDefinition::query()
            ->where('managed_environment_id', $tenant->getKey())
            ->where('entra_id', $roleId)
            ->value('display_name');

        $displayName = is_string($displayName) && $displayName !== '' ? $displayName : $roleId;

        return static::formatRoleLabel($displayName, $roleId);
    }

    private static function roleNameFromCache(?ManagedEnvironment $tenant, ?string $roleId): ?string
    {
        if (! $tenant || blank($roleId)) {
            return $roleId;
        }

        $displayName = EntraRoleDefinition::query()
            ->where('managed_environment_id', $tenant->getKey())
            ->where('entra_id', $roleId)
            ->value('display_name');

        return is_string($displayName) && $displayName !== '' ? $displayName : $roleId;
    }

    private static function formatRoleLabel(?string $displayName, string $id): string
    {
        $suffix = sprintf(' (%s)', Str::limit($id, 8, ''));

        return trim(($displayName ?: 'RBAC role').$suffix);
    }

    private static function loginToSearchGroupsAction(?ManagedEnvironment $tenant): ?Actions\Action
    {
        return null;
    }

    public static function groupSearchHelper(?ManagedEnvironment $tenant): ?string
    {
        if (! $tenant) {
            return null;
        }

        return static::delegatedToken($tenant) === null ? 'Login to search groups' : null;
    }

    /**
     * @return array<string, string>
     */
    public static function groupSearchOptions(?ManagedEnvironment $tenant, string $search): array
    {
        if (! $tenant || mb_strlen($search) < 2) {
            return [];
        }

        $token = static::delegatedToken($tenant);

        if ($token !== null) {
            /** @var GraphClientInterface $graph */
            $graph = app(GraphClientInterface::class);

            $response = $graph->request('GET', 'groups', [
                'access_token' => $token,
                'query' => [
                    '$filter' => sprintf("startswith(displayName,'%s') and securityEnabled eq true", addslashes($search)),
                ],
            ]);

            if ($response->failed()) {
                return [];
            }

            $groups = is_array($response->data['value'] ?? null) ? $response->data['value'] : [];
            $results = [];

            foreach ($groups as $group) {
                $id = is_string($group['id'] ?? null) ? (string) $group['id'] : null;
                $displayName = is_string($group['displayName'] ?? null) ? (string) $group['displayName'] : null;

                if (! $id || ! $displayName) {
                    continue;
                }

                $results[$id] = EntraGroupLabelResolver::formatLabel($displayName, $id);
            }

            ksort($results);

            return array_slice($results, 0, 20, true);
        }

        $needle = mb_strtolower($search);

        return EntraGroup::query()
            ->where('managed_environment_id', $tenant->getKey())
            ->whereRaw('lower(display_name) like ?', [$needle.'%'])
            ->orderBy('display_name')
            ->limit(20)
            ->get(['entra_id', 'display_name'])
            ->mapWithKeys(fn (EntraGroup $group): array => [
                (string) $group->entra_id => EntraGroupLabelResolver::formatLabel((string) $group->display_name, (string) $group->entra_id),
            ])
            ->all();
    }

    public static function groupLabelFromCache(?ManagedEnvironment $tenant, ?string $groupId): ?string
    {
        if (! $tenant || blank($groupId)) {
            return $groupId;
        }

        $resolver = app(EntraGroupLabelResolver::class);

        return $resolver->resolveOne($tenant, $groupId);
    }

    public static function syncRoleDefinitionsAction(): Actions\Action
    {
        return Actions\Action::make('sync_role_definitions')
            ->label('Sync now')
            ->icon('heroicon-o-arrow-path')
            ->color('warning')
            ->visible(fn (?ManagedEnvironment $record): bool => $record instanceof ManagedEnvironment && $record->isActive())
            ->action(function (ManagedEnvironment $record, RoleDefinitionsSyncService $syncService): void {
                $user = auth()->user();

                if (! $user instanceof User) {
                    abort(403);
                }

                if (! $user->canAccessTenant($record)) {
                    abort(404);
                }

                /** @var CapabilityResolver $resolver */
                $resolver = app(CapabilityResolver::class);

                if (! $resolver->can($user, $record, Capabilities::TENANT_MANAGE)) {
                    abort(403);
                }

                $result = $syncService->startManualSync($record, $user);
                $notification = app(ProviderOperationStartResultPresenter::class)->notification(
                    result: $result,
                    blockedTitle: 'Role definitions sync blocked',
                    runUrl: OperationRunLinks::tenantlessView($result->run),
                );

                $notification->send();
            });
    }
}
