<?php

namespace App\Filament\Resources;

use App\Filament\Concerns\InteractsWithTenantOwnedRecords;
use App\Filament\Concerns\ResolvesPanelTenantContext;
use App\Filament\Concerns\ScopesGlobalSearchToTenant;
use App\Filament\Concerns\WorkspaceScopedEnvironmentRoutes;
use App\Filament\Resources\PolicyResource\Pages;
use App\Filament\Resources\PolicyResource\RelationManagers\VersionsRelationManager;
use App\Filament\Support\NormalizedSettingsSurface;
use App\Jobs\BulkPolicyDeleteJob;
use App\Jobs\BulkPolicyExportJob;
use App\Jobs\BulkPolicyUnignoreJob;
use App\Jobs\SyncPoliciesJob;
use App\Models\ManagedEnvironment;
use App\Models\Policy;
use App\Models\User;
use App\Services\Auth\CapabilityResolver;
use App\Services\Intune\PolicyNormalizer;
use App\Services\OperationRunService;
use App\Services\Operations\BulkSelectionIdentity;
use App\Support\Auth\Capabilities;
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\Navigation\NavigationScope;
use App\Support\OperationRunLinks;
use App\Support\OpsUx\OperationUxPresenter;
use App\Support\OpsUx\OpsUxBrowserEvents;
use App\Support\Rbac\UiEnforcement;
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 BackedEnum;
use Filament\Actions;
use Filament\Actions\ActionGroup;
use Filament\Actions\BulkAction;
use Filament\Actions\BulkActionGroup;
use Filament\Forms;
use Filament\Infolists\Components\TextEntry;
use Filament\Infolists\Components\ViewEntry;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Tabs;
use Filament\Schemas\Components\Tabs\Tab;
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\Collection;
use UnitEnum;

class PolicyResource extends Resource
{
    use InteractsWithTenantOwnedRecords;
    use ResolvesPanelTenantContext;
    use ScopesGlobalSearchToTenant;
    use WorkspaceScopedEnvironmentRoutes;

    protected static ?string $model = Policy::class;

    protected static ?string $tenantOwnershipRelationshipName = 'tenant';

    protected static bool $isGloballySearchable = false;

    protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-shield-check';

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

    public static function getModelLabel(): string
    {
        return static::text('common.policy');
    }

    public static function getPluralModelLabel(): string
    {
        return static::text('common.policies');
    }

    public static function shouldRegisterNavigation(): bool
    {
        return NavigationScope::shouldRegisterEnvironmentNavigation()
            && parent::shouldRegisterNavigation();
    }

    public static function canViewAny(): bool
    {
        $tenant = static::resolveTenantContextForCurrentPanel();
        $user = auth()->user();

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

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

        return $resolver->isMember($user, $tenant)
            && $resolver->can($user, $tenant, Capabilities::TENANT_VIEW);
    }

    public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
    {
        return ActionSurfaceDeclaration::forResource(ActionSurfaceProfile::CrudListAndView, ActionSurfaceType::CrudListFirstResource)
            ->satisfy(ActionSurfaceSlot::ListHeader, 'Header action: Sync policies.')
            ->satisfy(ActionSurfaceSlot::InspectAffordance, ActionSurfaceInspectAffordance::ClickableRow->value)
            ->satisfy(ActionSurfaceSlot::ListRowMoreMenu, 'Secondary row actions are grouped under "More" in helper-first, workflow-next, destructive-last order.')
            ->satisfy(ActionSurfaceSlot::ListBulkMoreGroup, 'Bulk actions are grouped under "More" in helper-first, workflow-next, destructive-last order.')
            ->satisfy(ActionSurfaceSlot::ListEmptyState, 'List page defines an empty-state CTA.')
            ->satisfy(ActionSurfaceSlot::DetailHeader, 'View page provides header actions when applicable.');
    }

    public static function makeSyncAction(string $name = 'sync'): Actions\Action
    {
        return UiEnforcement::forAction(
            Actions\Action::make($name)
                ->label(static::text('resource.sync_action_primary'))
                ->icon('heroicon-o-arrow-path')
                ->color('primary')
                ->requiresConfirmation()
                ->modalHeading(static::text('resource.sync_modal_heading'))
                ->modalDescription(static::text('resource.sync_modal_description').' '.static::text('common.source_microsoft_intune'))
                ->action(function (Pages\ListPolicies $livewire): void {
                    $tenant = static::resolveTenantContextForCurrentPanel();
                    $user = auth()->user();

                    if (! $user instanceof User || ! $tenant instanceof ManagedEnvironment) {
                        abort(404);
                    }

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

                    sort($requestedTypes);

                    /** @var OperationRunService $opService */
                    $opService = app(OperationRunService::class);
                    $opRun = $opService->ensureRun(
                        tenant: $tenant,
                        type: 'policy.sync',
                        inputs: [
                            'scope' => 'all',
                            'types' => $requestedTypes,
                        ],
                        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(static::text('common.open_operation'))
                                    ->url(OperationRunLinks::view($opRun, $tenant)),
                            ])
                            ->send();

                        return;
                    }

                    $opService->dispatchOrFail($opRun, function () use ($tenant, $requestedTypes, $opRun): void {
                        SyncPoliciesJob::dispatch((int) $tenant->getKey(), $requestedTypes, null, $opRun);
                    });
                    OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
                    OperationUxPresenter::queuedToast((string) $opRun->type)
                        ->actions([
                            Actions\Action::make('view_run')
                                ->label(static::text('common.open_operation'))
                                ->url(OperationRunLinks::view($opRun, $tenant)),
                        ])
                        ->send();
                })
        )
            ->requireCapability(Capabilities::TENANT_SYNC)
            ->tooltip(static::text('resource.sync_permission_tooltip'))
            ->apply();
    }

    public static function form(Schema $schema): Schema
    {
        return $schema;
    }

    public static function infolist(Schema $schema): Schema
    {
        return $schema
            ->schema([
                Section::make(static::text('resource.details_section'))
                    ->schema([
                        TextEntry::make('display_name')->label(static::text('common.policy')),
                        TextEntry::make('policy_type')->label(static::text('common.type')),
                        TextEntry::make('platform')
                            ->label(static::text('common.platform'))
                            ->badge()
                            ->formatStateUsing(TagBadgeRenderer::label(TagBadgeDomain::Platform))
                            ->color(TagBadgeRenderer::color(TagBadgeDomain::Platform)),
                        TextEntry::make('visibility_state')
                            ->label(static::text('common.visibility'))
                            ->badge()
                            ->state(fn (Policy $record): string => $record->visibilityState())
                            ->formatStateUsing(BadgeRenderer::label(BadgeDomain::PolicyProviderPresence))
                            ->color(BadgeRenderer::color(BadgeDomain::PolicyProviderPresence))
                            ->icon(BadgeRenderer::icon(BadgeDomain::PolicyProviderPresence))
                            ->iconColor(BadgeRenderer::iconColor(BadgeDomain::PolicyProviderPresence))
                            ->helperText(fn (Policy $record): ?string => $record->isProviderMissing()
                                ? static::text('resource.visibility_source_unavailable_backup_items')
                                : null),
                        TextEntry::make('external_id')->label(static::text('common.external_id')),
                        TextEntry::make('last_synced_at')->dateTime()->label(static::text('common.last_synced')),
                        TextEntry::make('created_at')->since()->label(static::text('common.created')),
                        TextEntry::make('latest_snapshot_mode')
                            ->label(static::text('common.snapshot'))
                            ->badge()
                            ->formatStateUsing(BadgeRenderer::label(BadgeDomain::PolicySnapshotMode))
                            ->color(BadgeRenderer::color(BadgeDomain::PolicySnapshotMode))
                            ->icon(BadgeRenderer::icon(BadgeDomain::PolicySnapshotMode))
                            ->iconColor(BadgeRenderer::iconColor(BadgeDomain::PolicySnapshotMode))
                            ->state(fn (Policy $record): string => (static::latestVersionMetadata($record)['source'] ?? null) === 'metadata_only' ? 'metadata_only' : 'full')
                            ->helperText(function (Policy $record): ?string {
                                $meta = static::latestVersionMetadata($record);

                                if (($meta['source'] ?? null) !== 'metadata_only') {
                                    return null;
                                }

                                $status = $meta['original_status'] ?? null;

                                return sprintf(
                                    static::text('resource.snapshot_metadata_only_helper'),
                                    $status ?? static::text('resource.graph_error_fallback')
                                );
                            })
                            ->visible(fn (Policy $record) => $record->versions()->exists()),
                    ])
                    ->columns(2)
                    ->columnSpanFull(),

                // Tabbed content (General / Settings / JSON)
                Tabs::make('policy_content')
                    ->activeTab(1)
                    ->persistTabInQueryString()
                    ->tabs([
                        Tab::make(static::text('resource.tab_general'))
                            ->id('general')
                            ->schema([
                                ViewEntry::make('policy_general')
                                    ->label('')
                                    ->view('filament.infolists.entries.policy-general')
                                    ->state(function (Policy $record) {
                                        return static::generalOverviewState($record);
                                    }),
                            ])
                            ->visible(fn (Policy $record) => $record->versions()->exists()),
                        Tab::make(static::text('common.settings'))
                            ->id('settings')
                            ->schema([
                                ViewEntry::make('settings')
                                    ->label('')
                                    ->view('filament.infolists.entries.normalized-settings')
                                    ->state(function (Policy $record) {
                                        return NormalizedSettingsSurface::build(static::settingsTabState($record), 'policy');
                                    })
                                    ->visible(fn (Policy $record) => $record->versions()->exists()),

                                TextEntry::make('no_settings_available')
                                    ->label(static::text('common.settings'))
                                    ->state(static::text('resource.settings_empty_state'))
                                    ->helperText(static::text('resource.settings_empty_state_helper'))
                                    ->visible(fn (Policy $record) => ! $record->versions()->exists()),
                            ]),
                        Tab::make(static::text('resource.tab_json'))
                            ->id('json')
                            ->schema([
                                ViewEntry::make('snapshot_json')
                                    ->view('filament.infolists.entries.snapshot-json')
                                    ->state(fn (Policy $record) => static::latestSnapshot($record))
                                    ->columnSpanFull(),
                                TextEntry::make('snapshot_size')
                                    ->label(static::text('resource.payload_size'))
                                    ->state(fn (Policy $record) => strlen(json_encode(static::latestSnapshot($record) ?: [])))
                                    ->formatStateUsing(function ($state) {
                                        if ($state > 512000) {
                                            return '<span class="inline-flex items-center gap-1 text-warning-600 dark:text-warning-400 font-semibold">
                                                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                                                    <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
                                                </svg>
                                                '.static::text('resource.large_payload_warning', ['size' => number_format($state / 1024, 0)]).'
                                            </span>';
                                        }

                                        return number_format($state / 1024, 1).' KB';
                                    })
                                    ->html()
                                    ->visible(fn (Policy $record) => strlen(json_encode(static::latestSnapshot($record) ?: [])) > 512000),
                            ])
                            ->visible(fn (Policy $record) => $record->versions()->exists()),
                    ])
                    ->columnSpanFull()
                    ->visible(fn (Policy $record) => static::usesTabbedLayout($record)),

                // Legacy layout (kept for fallback if tabs are disabled)
                Section::make(static::text('common.settings'))
                    ->schema([
                        ViewEntry::make('settings')
                            ->label('')
                            ->view('filament.infolists.entries.normalized-settings')
                            ->state(function (Policy $record) {
                                return NormalizedSettingsSurface::build(static::settingsTabState($record), 'policy');
                            }),
                    ])
                    ->columnSpanFull()
                    ->visible(function (Policy $record) {
                        return ! static::usesTabbedLayout($record);
                    }),

                Section::make(static::text('resource.snapshot_json_section'))
                    ->schema([
                        ViewEntry::make('snapshot_json')
                            ->view('filament.infolists.entries.snapshot-json')
                            ->state(fn (Policy $record) => static::latestSnapshot($record))
                            ->columnSpanFull(),

                        TextEntry::make('snapshot_size')
                            ->label(static::text('resource.payload_size'))
                            ->state(fn (Policy $record) => strlen(json_encode(static::latestSnapshot($record) ?: [])))
                            ->formatStateUsing(function ($state) {
                                if ($state > 512000) {
                                    return '<span class="inline-flex items-center gap-1 text-warning-600 dark:text-warning-400 font-semibold">
                                        <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                                            <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
                                        </svg>
                                        '.static::text('resource.large_payload_warning', ['size' => number_format($state / 1024, 0)]).'
                                    </span>';
                                }

                                return number_format($state / 1024, 1).' KB';
                            })
                            ->html()
                            ->visible(fn (Policy $record) => strlen(json_encode(static::latestSnapshot($record) ?: [])) > 512000),
                    ])
                    ->collapsible()
                    ->collapsed(fn (Policy $record) => strlen(json_encode(static::latestSnapshot($record) ?: [])) > 512000)
                    ->description('Raw JSON configuration from Microsoft Graph API')
                    ->columnSpanFull()
                    ->visible(function (Policy $record) {
                        return ! static::usesTabbedLayout($record);
                    }),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('display_name')
            ->paginated(TablePaginationProfiles::resource())
            ->persistFiltersInSession()
            ->persistSearchInSession()
            ->persistSortInSession()
            ->recordUrl(fn (Policy $record): string => static::getUrl('view', ['record' => $record]))
            ->columns([
                Tables\Columns\TextColumn::make('display_name')
                    ->label(static::text('common.policy'))
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('policy_type')
                    ->label(static::text('common.type'))
                    ->badge()
                    ->formatStateUsing(TagBadgeRenderer::label(TagBadgeDomain::PolicyType))
                    ->color(TagBadgeRenderer::color(TagBadgeDomain::PolicyType))
                    ->icon(TagBadgeRenderer::icon(TagBadgeDomain::PolicyType))
                    ->iconColor(TagBadgeRenderer::iconColor(TagBadgeDomain::PolicyType)),
                Tables\Columns\TextColumn::make('visibility_state')
                    ->label(static::text('common.visibility'))
                    ->badge()
                    ->state(fn (Policy $record): string => $record->visibilityState())
                    ->formatStateUsing(BadgeRenderer::label(BadgeDomain::PolicyProviderPresence))
                    ->color(BadgeRenderer::color(BadgeDomain::PolicyProviderPresence))
                    ->icon(BadgeRenderer::icon(BadgeDomain::PolicyProviderPresence))
                    ->iconColor(BadgeRenderer::iconColor(BadgeDomain::PolicyProviderPresence))
                    ->description(fn (Policy $record): ?string => $record->isProviderMissing()
                        ? static::text('resource.visibility_source_unavailable_description')
                        : null),
                Tables\Columns\TextColumn::make('category')
                    ->label(static::text('common.category'))
                    ->badge()
                    ->state(fn (Policy $record) => static::typeMeta($record->policy_type)['category'] ?? null)
                    ->formatStateUsing(TagBadgeRenderer::label(TagBadgeDomain::PolicyCategory))
                    ->color(TagBadgeRenderer::color(TagBadgeDomain::PolicyCategory))
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('restore_mode')
                    ->label(static::text('common.restore'))
                    ->badge()
                    ->state(fn (Policy $record) => static::typeMeta($record->policy_type)['restore'] ?? 'enabled')
                    ->formatStateUsing(BadgeRenderer::label(BadgeDomain::PolicyRestoreMode))
                    ->color(BadgeRenderer::color(BadgeDomain::PolicyRestoreMode))
                    ->icon(BadgeRenderer::icon(BadgeDomain::PolicyRestoreMode))
                    ->iconColor(BadgeRenderer::iconColor(BadgeDomain::PolicyRestoreMode)),
                Tables\Columns\TextColumn::make('platform')
                    ->label(static::text('common.platform'))
                    ->badge()
                    ->formatStateUsing(TagBadgeRenderer::label(TagBadgeDomain::Platform))
                    ->color(TagBadgeRenderer::color(TagBadgeDomain::Platform))
                    ->sortable(),
                Tables\Columns\TextColumn::make('settings_status')
                    ->label(static::text('common.settings'))
                    ->badge()
                    ->state(function (Policy $record) {
                        $latest = $record->versions->first();
                        $snapshot = $latest?->snapshot ?? [];
                        $hasSettings = is_array($snapshot) && ! empty($snapshot['settings']);

                        return $hasSettings
                            ? static::text('resource.settings_available')
                            : static::text('resource.settings_missing');
                    })
                    ->color(function (Policy $record) {
                        $latest = $record->versions->first();
                        $snapshot = $latest?->snapshot ?? [];
                        $hasSettings = is_array($snapshot) && ! empty($snapshot['settings']);

                        return $hasSettings ? 'success' : 'gray';
                    }),
                Tables\Columns\TextColumn::make('external_id')
                    ->label(static::text('common.external_id'))
                    ->copyable()
                    ->limit(32)
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('last_synced_at')
                    ->label(static::text('common.last_synced'))
                    ->dateTime()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->since()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('visibility')
                    ->label(static::text('common.visibility'))
                    ->options([
                        'active' => static::text('resource.filter_active'),
                        'ignored' => static::text('resource.filter_ignored'),
                        'provider_missing' => static::text('resource.filter_source_unavailable'),
                        'all' => static::text('resource.filter_all'),
                    ])
                    ->default('active')
                    ->query(function (Builder $query, array $data) {
                        $value = $data['value'] ?? null;

                        if (blank($value) || $value === 'all') {
                            return;
                        }

                        if ($value === 'active') {
                            $query->active();

                            return;
                        }

                        if ($value === 'ignored') {
                            $query->whereNotNull('ignored_at');

                            return;
                        }

                        if ($value === 'provider_missing') {
                            $query->whereNotNull('missing_from_provider_at');
                        }
                    }),
                Tables\Filters\SelectFilter::make('policy_type')
                    ->options(function () {
                        return collect(config('tenantpilot.supported_policy_types', []))
                            ->pluck('label', 'type')
                            ->map(fn ($label, $type) => $label ?? $type)
                            ->all();
                    }),
                Tables\Filters\SelectFilter::make('category')
                    ->options(function () {
                        return collect(config('tenantpilot.supported_policy_types', []))
                            ->pluck('category', 'category')
                            ->filter()
                            ->unique()
                            ->sort()
                            ->all();
                    })
                    ->query(function (Builder $query, array $data) {
                        $category = $data['value'] ?? null;
                        if (! $category) {
                            return;
                        }

                        $types = collect(config('tenantpilot.supported_policy_types', []))
                            ->where('category', $category)
                            ->pluck('type')
                            ->all();

                        $query->whereIn('policy_type', $types);
                    }),
                Tables\Filters\SelectFilter::make('platform')
                    ->options(fn () => Policy::query()
                        ->distinct()
                        ->pluck('platform', 'platform')
                        ->filter()
                        ->reject(fn ($platform) => is_string($platform) && strtolower($platform) === 'all')
                        ->all()),
            ])
            ->actions([
                ActionGroup::make([
                    UiEnforcement::forTableAction(
                        Actions\Action::make('export')
                            ->label(static::text('resource.export_to_backup'))
                            ->icon('heroicon-o-archive-box-arrow-down')
                            ->visible(fn (Policy $record): bool => $record->ignored_at === null)
                            ->disabled(fn (Policy $record): bool => ! $record->isCurrentBackupEligible())
                            ->tooltip(fn (Policy $record): ?string => $record->currentBackupBlockedReasonLabel())
                            ->form([
                                Forms\Components\TextInput::make('backup_name')
                                    ->label(static::text('common.backup_name'))
                                    ->required()
                                    ->default(fn () => static::text('common.backup_name_default_prefix').' '.now()->toDateTimeString()),
                            ])
                            ->action(function (Policy $record, array $data): void {
                                $tenant = static::resolveTenantContextForCurrentPanel();
                                $user = auth()->user();

                                if (! $tenant instanceof ManagedEnvironment) {
                                    abort(404);
                                }

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

                                if (! $record->isCurrentBackupEligible()) {
                                    Notification::make()
                                        ->title(static::text('resource.current_backup_unavailable'))
                                        ->body($record->currentBackupBlockedReasonLabel())
                                        ->warning()
                                        ->send();

                                    return;
                                }

                                $ids = [(int) $record->getKey()];

                                /** @var BulkSelectionIdentity $selection */
                                $selection = app(BulkSelectionIdentity::class);

                                $selectionIdentity = $selection->fromIds($ids);

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

                                $opRun = $runs->enqueueBulkOperation(
                                    tenant: $tenant,
                                    type: 'policy.export',
                                    targetScope: [
                                        'entra_tenant_id' => (string) ($tenant->managed_environment_id ?? $tenant->external_id),
                                    ],
                                    selectionIdentity: $selectionIdentity,
                                    dispatcher: function ($operationRun) use ($tenant, $user, $ids, $data): void {
                                        BulkPolicyExportJob::dispatchSync(
                                            tenantId: (int) $tenant->getKey(),
                                            userId: (int) $user->getKey(),
                                            policyIds: $ids,
                                            backupName: (string) $data['backup_name'],
                                            operationRun: $operationRun,
                                        );
                                    },
                                    initiator: $user,
                                    extraContext: [
                                        'backup_name' => (string) $data['backup_name'],
                                        'policy_count' => 1,
                                    ],
                                    emitQueuedNotification: false,
                                );

                                OperationUxPresenter::queuedToast((string) $opRun->type)
                                    ->actions([
                                        Actions\Action::make('view_run')
                                            ->label(static::text('common.open_operation'))
                                            ->url(OperationRunLinks::view($opRun, $tenant)),
                                    ])
                                    ->send();
                            }),
                        fn () => static::resolveTenantContextForCurrentPanel(),
                    )
                        ->requireCapability(Capabilities::TENANT_MANAGE)
                        ->preserveDisabled()
                        ->preserveVisibility()
                        ->apply(),
                    UiEnforcement::forTableAction(
                        Actions\Action::make('sync')
                            ->label(static::text('resource.sync_action_secondary'))
                            ->icon('heroicon-o-arrow-path')
                            ->color('primary')
                            ->requiresConfirmation()
                            ->visible(fn (Policy $record): bool => $record->ignored_at === null)
                            ->action(function (Policy $record, HasTable $livewire): void {
                                $tenant = static::resolveTenantContextForCurrentPanel();
                                $user = auth()->user();

                                if (! $tenant instanceof ManagedEnvironment) {
                                    abort(404);
                                }

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

                                /** @var OperationRunService $opService */
                                $opService = app(OperationRunService::class);
                                $opRun = $opService->ensureRun(
                                    tenant: $tenant,
                                    type: 'policy.sync_one',
                                    inputs: [
                                        'scope' => 'one',
                                        'policy_id' => (int) $record->getKey(),
                                    ],
                                    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(static::text('common.open_operation'))
                                                ->url(OperationRunLinks::view($opRun, $tenant)),
                                        ])
                                        ->send();

                                    return;
                                }

                                SyncPoliciesJob::dispatch((int) $tenant->getKey(), null, [(int) $record->getKey()], $opRun);
                                OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
                                OperationUxPresenter::queuedToast((string) $opRun->type)
                                    ->actions([
                                        Actions\Action::make('view_run')
                                            ->label(static::text('common.open_operation'))
                                            ->url(OperationRunLinks::view($opRun, $tenant)),
                                    ])
                                    ->send();
                            }),
                        fn () => static::resolveTenantContextForCurrentPanel(),
                    )
                        ->requireCapability(Capabilities::TENANT_SYNC)
                        ->preserveVisibility()
                        ->apply(),
                    UiEnforcement::forTableAction(
                        Actions\Action::make('restore')
                            ->label(static::text('resource.restore_action'))
                            ->icon('heroicon-o-arrow-uturn-left')
                            ->color('success')
                            ->requiresConfirmation()
                            ->visible(fn (Policy $record): bool => $record->ignored_at !== null)
                            ->action(function (Policy $record): void {
                                $record->unignore();

                                Notification::make()
                                    ->title(static::text('resource.policy_restored'))
                                    ->success()
                                    ->send();
                            }),
                        fn () => static::resolveTenantContextForCurrentPanel(),
                    )
                        ->requireCapability(Capabilities::TENANT_MANAGE)
                        ->tooltip(static::text('resource.restore_permission_tooltip'))
                        ->preserveVisibility()
                        ->apply(),
                    UiEnforcement::forTableAction(
                        Actions\Action::make('ignore')
                            ->label(static::text('resource.ignore_action'))
                            ->icon('heroicon-o-trash')
                            ->color('danger')
                            ->requiresConfirmation()
                            ->visible(fn (Policy $record): bool => $record->ignored_at === null)
                            ->action(function (Policy $record): void {
                                $record->ignore();

                                Notification::make()
                                    ->title(static::text('resource.policy_ignored'))
                                    ->success()
                                    ->send();
                            }),
                        fn () => static::resolveTenantContextForCurrentPanel(),
                    )
                        ->requireCapability(Capabilities::TENANT_MANAGE)
                        ->tooltip(static::text('resource.ignore_permission_tooltip'))
                        ->preserveVisibility()
                        ->apply(),
                ])
                    ->label(static::text('common.more'))
                    ->icon('heroicon-o-ellipsis-vertical'),
            ])
            ->bulkActions([
                BulkActionGroup::make([
                    UiEnforcement::forBulkAction(
                        BulkAction::make('bulk_export')
                            ->label(static::text('resource.export_to_backup'))
                            ->icon('heroicon-o-archive-box-arrow-down')
                            ->form([
                                Forms\Components\TextInput::make('backup_name')
                                    ->label(static::text('common.backup_name'))
                                    ->required()
                                    ->default(fn () => static::text('common.backup_name_default_prefix').' '.now()->toDateTimeString()),
                            ])
                            ->action(function (Collection $records, array $data): void {
                                $tenant = static::resolveTenantContextForCurrentPanel();
                                $user = auth()->user();
                                $count = $records->count();
                                $ids = $records->pluck('id')->toArray();

                                if (! $tenant instanceof ManagedEnvironment) {
                                    abort(404);
                                }

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

                                $blocked = $records->first(
                                    fn ($record): bool => $record instanceof Policy && ! $record->isCurrentBackupEligible()
                                );

                                if ($blocked instanceof Policy) {
                                    Notification::make()
                                        ->title(static::text('resource.current_backup_unavailable'))
                                        ->body($blocked->currentBackupBlockedReasonLabel())
                                        ->warning()
                                        ->send();

                                    return;
                                }

                                /** @var BulkSelectionIdentity $selection */
                                $selection = app(BulkSelectionIdentity::class);

                                $selectionIdentity = $selection->fromIds($ids);

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

                                $opRun = $runs->enqueueBulkOperation(
                                    tenant: $tenant,
                                    type: 'policy.export',
                                    targetScope: [
                                        'entra_tenant_id' => (string) ($tenant->managed_environment_id ?? $tenant->external_id),
                                    ],
                                    selectionIdentity: $selectionIdentity,
                                    dispatcher: function ($operationRun) use ($tenant, $user, $ids, $data, $count): void {
                                        if ($count >= 20) {
                                            BulkPolicyExportJob::dispatch(
                                                tenantId: (int) $tenant->getKey(),
                                                userId: (int) $user->getKey(),
                                                policyIds: $ids,
                                                backupName: (string) $data['backup_name'],
                                                operationRun: $operationRun,
                                            );

                                            return;
                                        }

                                        BulkPolicyExportJob::dispatchSync(
                                            tenantId: (int) $tenant->getKey(),
                                            userId: (int) $user->getKey(),
                                            policyIds: $ids,
                                            backupName: (string) $data['backup_name'],
                                            operationRun: $operationRun,
                                        );
                                    },
                                    initiator: $user,
                                    extraContext: [
                                        'backup_name' => (string) $data['backup_name'],
                                        'policy_count' => $count,
                                    ],
                                    emitQueuedNotification: false,
                                );

                                OperationUxPresenter::queuedToast((string) $opRun->type)
                                    ->actions([
                                        Actions\Action::make('view_run')
                                            ->label(static::text('common.open_operation'))
                                            ->url(OperationRunLinks::view($opRun, $tenant)),
                                    ])
                                    ->send();
                            })
                            ->deselectRecordsAfterCompletion(),
                    )
                        ->requireCapability(Capabilities::TENANT_MANAGE)
                        ->apply(),
                    UiEnforcement::forBulkAction(
                        BulkAction::make('bulk_sync')
                            ->label(static::text('resource.sync_action_primary'))
                            ->icon('heroicon-o-arrow-path')
                            ->color('primary')
                            ->requiresConfirmation()
                            ->hidden(function (HasTable $livewire): bool {
                                $visibilityFilterState = $livewire->getTableFilterState('visibility') ?? [];
                                $value = $visibilityFilterState['value'] ?? null;

                                return $value === 'ignored';
                            })
                            ->action(function (Collection $records, HasTable $livewire): void {
                                $tenant = static::resolveTenantContextForCurrentPanel();
                                $user = auth()->user();

                                if (! $tenant instanceof ManagedEnvironment) {
                                    abort(404);
                                }

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

                                $ids = $records
                                    ->pluck('id')
                                    ->map(static fn ($id): int => (int) $id)
                                    ->unique()
                                    ->sort()
                                    ->values()
                                    ->all();

                                /** @var OperationRunService $opService */
                                $opService = app(OperationRunService::class);
                                $opRun = $opService->ensureRun(
                                    tenant: $tenant,
                                    type: 'policy.sync',
                                    inputs: [
                                        'scope' => 'subset',
                                        'policy_ids' => $ids,
                                    ],
                                    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(static::text('common.open_operation'))
                                                ->url(OperationRunLinks::view($opRun, $tenant)),
                                        ])
                                        ->send();

                                    return;
                                }

                                SyncPoliciesJob::dispatch((int) $tenant->getKey(), null, $ids, $opRun);
                                OpsUxBrowserEvents::dispatchRunEnqueued($livewire);
                                OperationUxPresenter::queuedToast((string) $opRun->type)
                                    ->actions([
                                        Actions\Action::make('view_run')
                                            ->label(static::text('common.open_operation'))
                                            ->url(OperationRunLinks::view($opRun, $tenant)),
                                    ])
                                    ->send();
                            })
                            ->deselectRecordsAfterCompletion(),
                    )
                        ->requireCapability(Capabilities::TENANT_SYNC)
                        ->apply(),
                    UiEnforcement::forBulkAction(
                        BulkAction::make('bulk_restore')
                            ->label(static::text('resource.restore_bulk_action'))
                            ->icon('heroicon-o-arrow-uturn-left')
                            ->color('success')
                            ->requiresConfirmation()
                            ->hidden(function (HasTable $livewire): bool {
                                $visibilityFilterState = $livewire->getTableFilterState('visibility') ?? [];
                                $value = $visibilityFilterState['value'] ?? null;

                                return ! in_array($value, [null, 'ignored'], true);
                            })
                            ->action(function (Collection $records, HasTable $livewire): void {
                                $tenant = static::resolveTenantContextForCurrentPanel();
                                $user = auth()->user();
                                $count = $records->count();
                                $ids = $records->pluck('id')->toArray();

                                if (! $tenant instanceof ManagedEnvironment) {
                                    abort(404);
                                }

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

                                /** @var BulkSelectionIdentity $selection */
                                $selection = app(BulkSelectionIdentity::class);

                                $selectionIdentity = $selection->fromIds($ids);

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

                                $opRun = $runs->enqueueBulkOperation(
                                    tenant: $tenant,
                                    type: 'policy.unignore',
                                    targetScope: [
                                        'entra_tenant_id' => (string) ($tenant->managed_environment_id ?? $tenant->external_id),
                                    ],
                                    selectionIdentity: $selectionIdentity,
                                    dispatcher: function ($operationRun) use ($tenant, $user, $ids, $count): void {
                                        if ($count >= 20) {
                                            BulkPolicyUnignoreJob::dispatch(
                                                tenantId: (int) $tenant->getKey(),
                                                userId: (int) $user->getKey(),
                                                policyIds: $ids,
                                                operationRun: $operationRun,
                                            );

                                            return;
                                        }

                                        BulkPolicyUnignoreJob::dispatchSync(
                                            tenantId: (int) $tenant->getKey(),
                                            userId: (int) $user->getKey(),
                                            policyIds: $ids,
                                            operationRun: $operationRun,
                                        );
                                    },
                                    initiator: $user,
                                    extraContext: [
                                        'policy_count' => $count,
                                    ],
                                    emitQueuedNotification: false,
                                );

                                OpsUxBrowserEvents::dispatchRunEnqueued($livewire);

                                OperationUxPresenter::queuedToast((string) $opRun->type)
                                    ->actions([
                                        Actions\Action::make('view_run')
                                            ->label(static::text('common.open_operation'))
                                            ->url(OperationRunLinks::view($opRun, $tenant)),
                                    ])
                                    ->send();
                            })
                            ->deselectRecordsAfterCompletion(),
                    )
                        ->requireCapability(Capabilities::TENANT_MANAGE)
                        ->apply(),
                    UiEnforcement::forBulkAction(
                        BulkAction::make('bulk_delete')
                            ->label(static::text('resource.ignore_bulk_action'))
                            ->icon('heroicon-o-trash')
                            ->color('danger')
                            ->requiresConfirmation()
                            ->hidden(function (HasTable $livewire): bool {
                                $visibilityFilterState = $livewire->getTableFilterState('visibility') ?? [];
                                $value = $visibilityFilterState['value'] ?? null;

                                return $value === 'ignored';
                            })
                            ->form(function (Collection $records) {
                                if ($records->count() >= 20) {
                                    return [
                                        Forms\Components\TextInput::make('confirmation')
                                            ->label(static::text('common.type_delete_to_confirm'))
                                            ->required()
                                            ->in(['DELETE'])
                                            ->validationMessages([
                                                'in' => static::text('common.type_delete_to_confirm_validation'),
                                            ]),
                                    ];
                                }

                                return [];
                            })
                            ->action(function (Collection $records, HasTable $livewire): void {
                                $tenant = static::resolveTenantContextForCurrentPanel();
                                $user = auth()->user();
                                $count = $records->count();
                                $ids = $records->pluck('id')->toArray();

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

                                /** @var BulkSelectionIdentity $selection */
                                $selection = app(BulkSelectionIdentity::class);

                                $selectionIdentity = $selection->fromIds($ids);

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

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

                                $runUrl = OperationRunLinks::view($opRun, $tenant);

                                OpsUxBrowserEvents::dispatchRunEnqueued($livewire);

                                if (! $opRun->wasRecentlyCreated && in_array($opRun->status, ['queued', 'running'], true)) {
                                    OperationUxPresenter::alreadyQueuedToast((string) $opRun->type)
                                        ->body(static::text('resource.delete_queued_body', ['count' => $count]))
                                        ->actions([
                                            \Filament\Actions\Action::make('view_run')
                                                ->label(static::text('common.open_operation'))
                                                ->url($runUrl),
                                        ])
                                        ->send();

                                    return;
                                }

                                OperationUxPresenter::queuedToast((string) $opRun->type)
                                    ->body(static::text('resource.delete_queued_body', ['count' => $count]))
                                    ->actions([
                                        \Filament\Actions\Action::make('view_run')
                                            ->label(static::text('common.open_operation'))
                                            ->url($runUrl),
                                    ])
                                    ->send();
                            })
                            ->deselectRecordsAfterCompletion(),
                    )
                        ->requireCapability(Capabilities::TENANT_MANAGE)
                        ->apply(),
                ])->label(static::text('common.more')),
            ])
            ->emptyStateHeading(static::text('resource.empty_state_heading'))
            ->emptyStateDescription(static::text('resource.empty_state_description'))
            ->emptyStateIcon('heroicon-o-arrow-path')
            ->emptyStateActions([
                static::makeSyncAction(),
            ]);
    }

    public static function getEloquentQuery(): Builder
    {
        return static::getTenantOwnedEloquentQuery()
            ->withCount('versions')
            ->with([
                'versions' => fn ($query) => $query->orderByDesc('captured_at')->limit(1),
            ]);
    }

    public static function resolveScopedRecordOrFail(int|string $key): \Illuminate\Database\Eloquent\Model
    {
        return static::resolveTenantOwnedRecordOrFail(
            $key,
            parent::getEloquentQuery()
                ->withCount('versions')
                ->with([
                    'versions' => fn ($query) => $query->orderByDesc('captured_at')->limit(1),
                ]),
        );
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListPolicies::route('/'),
            'view' => Pages\ViewPolicy::route('/{record}'),
        ];
    }

    private static function latestSnapshot(Policy $record): array
    {
        $snapshot = $record->relationLoaded('versions')
            ? $record->versions->first()?->snapshot
            : $record->versions()->orderByDesc('captured_at')->value('snapshot');

        if (is_string($snapshot)) {
            $decoded = json_decode($snapshot, true);
            $snapshot = $decoded ?? [];
        }

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

        return [];
    }

    private static function latestVersionMetadata(Policy $record): array
    {
        $metadata = $record->relationLoaded('versions')
            ? $record->versions->first()?->metadata
            : $record->versions()->orderByDesc('captured_at')->value('metadata');

        if (is_string($metadata)) {
            $decoded = json_decode($metadata, true);
            $metadata = $decoded ?? [];
        }

        return is_array($metadata) ? $metadata : [];
    }

    /**
     * @return array<string, mixed>
     */
    private static function normalizedPolicyState(Policy $record): array
    {
        $cacheKey = 'tenantpilot.normalizedPolicyState.'.(string) $record->getKey();
        $request = request();

        if ($request->attributes->has($cacheKey)) {
            $cached = $request->attributes->get($cacheKey);

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

        $snapshot = static::latestSnapshot($record);

        $normalized = app(PolicyNormalizer::class)->normalize(
            $snapshot,
            $record->policy_type,
            $record->platform
        );

        $normalized['context'] = 'policy';
        $normalized['record_id'] = (string) $record->getKey();
        $normalized['policy_type'] = $record->policy_type;

        $request->attributes->set($cacheKey, $normalized);

        return $normalized;
    }

    /**
     * @param  array{settings?: array<int, array<string, mixed>>}  $normalized
     * @return array{normalized: array<string, mixed>, general: ?array<string, mixed>}
     */
    private static function splitGeneralBlock(array $normalized): array
    {
        $general = null;
        $filtered = [];

        foreach ($normalized['settings'] ?? [] as $block) {
            if (! is_array($block)) {
                continue;
            }

            $title = $block['title'] ?? null;

            if (is_string($title) && strtolower($title) === 'general') {
                $general = $block;

                continue;
            }

            $filtered[] = $block;
        }

        $normalized['settings'] = $filtered;

        return [
            'normalized' => $normalized,
            'general' => $general,
        ];
    }

    /**
     * @return array{label:?string,category:?string,restore:?string,risk:?string}|array<string,string>|array<string,mixed>
     */
    private static function typeMeta(?string $type): array
    {
        if ($type === null) {
            return [];
        }

        return collect(config('tenantpilot.supported_policy_types', []))
            ->firstWhere('type', $type) ?? [];
    }

    private static function usesTabbedLayout(Policy $record): bool
    {
        return true;
    }

    private static function hasSettingsTable(Policy $record): bool
    {
        $normalized = static::normalizedPolicyState($record);
        $rows = $normalized['settings_table']['rows'] ?? [];

        return is_array($rows) && $rows !== [];
    }

    /**
     * @return array{entries: array<int, array{key: string, value: mixed}>}
     */
    private static function generalOverviewState(Policy $record): array
    {
        $snapshot = static::latestSnapshot($record);
        $entries = [];

        $name = $snapshot['displayName'] ?? $snapshot['name'] ?? $record->display_name;
        if (is_string($name) && $name !== '') {
            $entries[] = ['key' => static::text('resource.general_field_name'), 'value' => $name];
        }

        $platforms = $snapshot['platforms'] ?? $snapshot['platform'] ?? $record->platform;
        if (is_string($platforms) && $platforms !== '') {
            $entries[] = ['key' => static::text('resource.general_field_platforms'), 'value' => $platforms];
        } elseif (is_array($platforms) && $platforms !== []) {
            $entries[] = ['key' => static::text('resource.general_field_platforms'), 'value' => $platforms];
        }

        $technologies = $snapshot['technologies'] ?? null;
        if (is_string($technologies) && $technologies !== '') {
            $entries[] = ['key' => static::text('resource.general_field_technologies'), 'value' => $technologies];
        } elseif (is_array($technologies) && $technologies !== []) {
            $entries[] = ['key' => static::text('resource.general_field_technologies'), 'value' => $technologies];
        }

        if (array_key_exists('templateReference', $snapshot)) {
            $entries[] = ['key' => static::text('resource.general_field_template_reference'), 'value' => $snapshot['templateReference']];
        }

        $settingCount = $snapshot['settingCount']
            ?? $snapshot['settingsCount']
            ?? (isset($snapshot['settings']) && is_array($snapshot['settings']) ? count($snapshot['settings']) : null);

        if (is_int($settingCount) || is_numeric($settingCount)) {
            $entries[] = ['key' => static::text('resource.general_field_setting_count'), 'value' => $settingCount];
        }

        $version = $snapshot['version'] ?? null;
        if (is_string($version) && $version !== '') {
            $entries[] = ['key' => static::text('resource.general_field_version'), 'value' => $version];
        } elseif (is_numeric($version)) {
            $entries[] = ['key' => static::text('resource.general_field_version'), 'value' => $version];
        }

        $lastModified = $snapshot['lastModifiedDateTime'] ?? null;
        if (is_string($lastModified) && $lastModified !== '') {
            $entries[] = ['key' => static::text('resource.general_field_last_modified'), 'value' => $lastModified];
        }

        $createdAt = $snapshot['createdDateTime'] ?? null;
        if (is_string($createdAt) && $createdAt !== '') {
            $entries[] = ['key' => static::text('resource.general_field_created'), 'value' => $createdAt];
        }

        $description = $snapshot['description'] ?? null;
        if (is_string($description) && $description !== '') {
            $entries[] = ['key' => static::text('resource.general_field_description'), 'value' => $description];
        }

        return [
            'entries' => $entries,
        ];
    }

    /**
     * @return array<string, mixed>
     */
    private static function settingsTabState(Policy $record): array
    {
        $normalized = static::normalizedPolicyState($record);
        $rows = $normalized['settings_table']['rows'] ?? [];
        $hasSettingsTable = is_array($rows) && $rows !== [];

        if (in_array($record->policy_type, ['settingsCatalogPolicy', 'endpointSecurityPolicy', 'securityBaselinePolicy'], true) && $hasSettingsTable) {
            $split = static::splitGeneralBlock($normalized);

            return $split['normalized'];
        }

        return $normalized;
    }

    private static function text(string $key, array $replace = []): string
    {
        return __('localization.policy.'.$key, $replace);
    }
}
