<?php

namespace App\Filament\Resources;

use App\Filament\Support\VerificationReportChangeIndicator;
use App\Filament\Support\VerificationReportViewer;
use App\Models\OperationRun;
use App\Models\Tenant;
use App\Models\User;
use App\Models\VerificationCheckAcknowledgement;
use App\Support\Badges\BadgeDomain;
use App\Support\Badges\BadgeRenderer;
use App\Support\Baselines\BaselineCompareReasonCode;
use App\Support\Filament\FilterOptionCatalog;
use App\Support\Filament\FilterPresets;
use App\Support\Filament\TablePaginationProfiles;
use App\Support\Navigation\CrossResourceNavigationMatrix;
use App\Support\Navigation\RelatedNavigationResolver;
use App\Support\OperateHub\OperateHubShell;
use App\Support\OperationCatalog;
use App\Support\OperationRunLinks;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\OpsUx\RunDetailPolling;
use App\Support\OpsUx\RunDurationInsights;
use App\Support\RedactionIntegrity;
use App\Support\Ui\ActionSurface\ActionSurfaceDeclaration;
use App\Support\Ui\ActionSurface\ActionSurfaceDefaults;
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceInspectAffordance;
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceProfile;
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceSlot;
use App\Support\Workspaces\WorkspaceContext;
use BackedEnum;
use Filament\Actions;
use Filament\Facades\Filament;
use Filament\Infolists\Components\TextEntry;
use Filament\Infolists\Components\ViewEntry;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use UnitEnum;

class OperationRunResource extends Resource
{
    protected static bool $isScopedToTenant = false;

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

    protected static ?string $slug = 'operations';

    protected static bool $shouldRegisterNavigation = false;

    protected static bool $isGloballySearchable = false;

    protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-queue-list';

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

    protected static ?string $navigationLabel = 'Operations';

    public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
    {
        return ActionSurfaceDeclaration::forResource(ActionSurfaceProfile::RunLog)
            ->withDefaults(new ActionSurfaceDefaults(
                moreGroupLabel: 'More',
                exportIsDefaultBulkActionForReadOnly: false,
            ))
            ->exempt(
                ActionSurfaceSlot::ListHeader,
                'Run-log list intentionally has no list-header actions; navigation actions are provided by Monitoring shell pages.',
            )
            ->satisfy(ActionSurfaceSlot::InspectAffordance, ActionSurfaceInspectAffordance::ViewAction->value)
            ->exempt(
                ActionSurfaceSlot::ListBulkMoreGroup,
                'Operation runs are immutable records; bulk export is deferred and tracked outside this retrofit.',
            )
            ->exempt(
                ActionSurfaceSlot::ListEmptyState,
                'Empty-state action is intentionally omitted; users can adjust filters/date range in-page.',
            )
            ->exempt(
                ActionSurfaceSlot::DetailHeader,
                'Tenantless detail view is informational and currently has no header actions.',
            );
    }

    public static function getEloquentQuery(): Builder
    {
        $workspaceId = app(WorkspaceContext::class)->currentWorkspaceId();

        return parent::getEloquentQuery()
            ->with('user')
            ->latest('id')
            ->when($workspaceId, fn (Builder $query) => $query->where('workspace_id', (int) $workspaceId))
            ->when(! $workspaceId, fn (Builder $query) => $query->whereRaw('1 = 0'));
    }

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

    public static function infolist(Schema $schema): Schema
    {
        return $schema
            ->schema([
                Section::make('Run')
                    ->schema([
                        TextEntry::make('type')
                            ->badge()
                            ->formatStateUsing(fn (?string $state): string => OperationCatalog::label((string) $state)),
                        TextEntry::make('status')
                            ->badge()
                            ->formatStateUsing(BadgeRenderer::label(BadgeDomain::OperationRunStatus))
                            ->color(BadgeRenderer::color(BadgeDomain::OperationRunStatus))
                            ->icon(BadgeRenderer::icon(BadgeDomain::OperationRunStatus))
                            ->iconColor(BadgeRenderer::iconColor(BadgeDomain::OperationRunStatus)),
                        TextEntry::make('outcome')
                            ->badge()
                            ->formatStateUsing(BadgeRenderer::label(BadgeDomain::OperationRunOutcome))
                            ->color(BadgeRenderer::color(BadgeDomain::OperationRunOutcome))
                            ->icon(BadgeRenderer::icon(BadgeDomain::OperationRunOutcome))
                            ->iconColor(BadgeRenderer::iconColor(BadgeDomain::OperationRunOutcome)),
                        TextEntry::make('initiator_name')->label('Initiator'),
                        TextEntry::make('target_scope_display')
                            ->label('Target')
                            ->getStateUsing(fn (OperationRun $record): ?string => static::targetScopeDisplay($record))
                            ->visible(fn (OperationRun $record): bool => static::targetScopeDisplay($record) !== null)
                            ->columnSpanFull(),
                        TextEntry::make('target_scope_empty_state')
                            ->label('Target')
                            ->getStateUsing(static fn (): string => 'No target scope details were recorded for this run.')
                            ->visible(fn (OperationRun $record): bool => static::targetScopeDisplay($record) === null)
                            ->columnSpanFull(),
                        TextEntry::make('elapsed')
                            ->label('Elapsed')
                            ->getStateUsing(fn (OperationRun $record): string => RunDurationInsights::elapsedHuman($record)),
                        TextEntry::make('expected_duration')
                            ->label('Expected')
                            ->getStateUsing(fn (OperationRun $record): string => RunDurationInsights::expectedHuman($record) ?? '—'),
                        TextEntry::make('stuck_guidance')
                            ->label('')
                            ->getStateUsing(fn (OperationRun $record): ?string => RunDurationInsights::stuckGuidance($record))
                            ->visible(fn (OperationRun $record): bool => RunDurationInsights::stuckGuidance($record) !== null),
                        TextEntry::make('created_at')->dateTime(),
                        TextEntry::make('started_at')->dateTime()->placeholder('—'),
                        TextEntry::make('completed_at')->dateTime()->placeholder('—'),
                        TextEntry::make('run_identity_hash')->label('Identity hash')->copyable(),
                    ])
                    ->extraAttributes([
                        'x-init' => '$wire.set(\'opsUxIsTabHidden\', document.hidden)',
                        'x-on:visibilitychange.window' => '$wire.set(\'opsUxIsTabHidden\', document.hidden)',
                    ])
                    ->poll(function (OperationRun $record, $livewire): ?string {
                        if (($livewire->opsUxIsTabHidden ?? false) === true) {
                            return null;
                        }

                        if (filled($livewire->mountedActions ?? null)) {
                            return null;
                        }

                        return RunDetailPolling::interval($record);
                    })
                    ->columns(2)
                    ->columnSpanFull(),

                Section::make('Counts')
                    ->schema([
                        ViewEntry::make('summary_counts')
                            ->label('')
                            ->view('filament.infolists.entries.snapshot-json')
                            ->state(fn (OperationRun $record): array => $record->summary_counts ?? [])
                            ->columnSpanFull(),
                    ])
                    ->visible(fn (OperationRun $record): bool => ! empty($record->summary_counts))
                    ->columnSpanFull(),

                Section::make('Related context')
                    ->schema([
                        ViewEntry::make('related_context')
                            ->label('')
                            ->view('filament.infolists.entries.related-context')
                            ->state(fn (OperationRun $record): array => app(RelatedNavigationResolver::class)
                                ->detailEntries(CrossResourceNavigationMatrix::SOURCE_OPERATION_RUN, $record))
                            ->columnSpanFull(),
                    ])
                    ->columnSpanFull(),

                Section::make('Failures')
                    ->schema([
                        ViewEntry::make('failure_summary')
                            ->label('')
                            ->view('filament.infolists.entries.snapshot-json')
                            ->state(fn (OperationRun $record): array => $record->failure_summary ?? [])
                            ->columnSpanFull(),
                    ])
                    ->visible(fn (OperationRun $record): bool => ! empty($record->failure_summary))
                    ->columnSpanFull(),

                Section::make('Baseline compare')
                    ->schema([
                        TextEntry::make('baseline_compare_fidelity')
                            ->label('Fidelity')
                            ->badge()
                            ->getStateUsing(function (OperationRun $record): string {
                                $context = is_array($record->context) ? $record->context : [];
                                $fidelity = data_get($context, 'baseline_compare.fidelity');

                                return is_string($fidelity) && $fidelity !== '' ? $fidelity : 'meta';
                            }),
                        TextEntry::make('baseline_compare_coverage_status')
                            ->label('Coverage')
                            ->badge()
                            ->getStateUsing(function (OperationRun $record): string {
                                $context = is_array($record->context) ? $record->context : [];
                                $proof = data_get($context, 'baseline_compare.coverage.proof');
                                $proof = is_bool($proof) ? $proof : null;

                                $uncovered = data_get($context, 'baseline_compare.coverage.uncovered_types');
                                $uncovered = is_array($uncovered) ? array_values(array_filter($uncovered, 'is_string')) : [];

                                return match (true) {
                                    $proof === false => 'unproven',
                                    $uncovered !== [] => 'warnings',
                                    $proof === true => 'ok',
                                    default => 'unknown',
                                };
                            })
                            ->color(fn (?string $state): string => match ((string) $state) {
                                'ok' => 'success',
                                'warnings', 'unproven' => 'warning',
                                default => 'gray',
                            }),
                        TextEntry::make('baseline_compare_why_no_findings')
                            ->label('Why no findings')
                            ->getStateUsing(function (OperationRun $record): ?string {
                                $context = is_array($record->context) ? $record->context : [];
                                $code = data_get($context, 'baseline_compare.reason_code');
                                $code = is_string($code) ? trim($code) : null;
                                $code = $code !== '' ? $code : null;

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

                                $enum = BaselineCompareReasonCode::tryFrom($code);
                                $message = $enum?->message();

                                return ($message !== null ? $message.' (' : '').$code.($message !== null ? ')' : '');
                            })
                            ->visible(function (OperationRun $record): bool {
                                $context = is_array($record->context) ? $record->context : [];
                                $code = data_get($context, 'baseline_compare.reason_code');

                                return is_string($code) && trim($code) !== '';
                            })
                            ->columnSpanFull(),
                        TextEntry::make('baseline_compare_uncovered_types')
                            ->label('Uncovered types')
                            ->getStateUsing(function (OperationRun $record): ?string {
                                $context = is_array($record->context) ? $record->context : [];
                                $types = data_get($context, 'baseline_compare.coverage.uncovered_types');
                                $types = is_array($types) ? array_values(array_filter($types, 'is_string')) : [];
                                $types = array_values(array_unique(array_filter(array_map('trim', $types), fn (string $type): bool => $type !== '')));

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

                                sort($types, SORT_STRING);

                                return implode(', ', array_slice($types, 0, 12)).(count($types) > 12 ? '…' : '');
                            })
                            ->visible(function (OperationRun $record): bool {
                                $context = is_array($record->context) ? $record->context : [];
                                $types = data_get($context, 'baseline_compare.coverage.uncovered_types');

                                return is_array($types) && $types !== [];
                            })
                            ->columnSpanFull(),
                        TextEntry::make('baseline_compare_inventory_sync_run_id')
                            ->label('Inventory sync run')
                            ->getStateUsing(function (OperationRun $record): ?string {
                                $context = is_array($record->context) ? $record->context : [];
                                $syncRunId = data_get($context, 'baseline_compare.inventory_sync_run_id');

                                return is_numeric($syncRunId) ? '#'.(string) (int) $syncRunId : null;
                            })
                            ->visible(function (OperationRun $record): bool {
                                $context = is_array($record->context) ? $record->context : [];

                                return is_numeric(data_get($context, 'baseline_compare.inventory_sync_run_id'));
                            }),
                    ])
                    ->visible(fn (OperationRun $record): bool => (string) $record->type === 'baseline_compare')
                    ->columns(2)
                    ->columnSpanFull(),

                Section::make('Baseline compare evidence')
                    ->schema([
                        TextEntry::make('baseline_compare_subjects_total')
                            ->label('Subjects total')
                            ->getStateUsing(function (OperationRun $record): ?int {
                                $context = is_array($record->context) ? $record->context : [];
                                $value = data_get($context, 'baseline_compare.subjects_total');

                                return is_numeric($value) ? (int) $value : null;
                            })
                            ->placeholder('—'),
                        TextEntry::make('baseline_compare_gap_count')
                            ->label('Evidence gaps')
                            ->getStateUsing(function (OperationRun $record): ?int {
                                $context = is_array($record->context) ? $record->context : [];
                                $value = data_get($context, 'baseline_compare.evidence_gaps.count');

                                return is_numeric($value) ? (int) $value : null;
                            })
                            ->placeholder('—'),
                        TextEntry::make('baseline_compare_resume_token')
                            ->label('Resume token')
                            ->getStateUsing(function (OperationRun $record): ?string {
                                $context = is_array($record->context) ? $record->context : [];
                                $value = data_get($context, 'baseline_compare.resume_token');

                                return is_string($value) && $value !== '' ? $value : null;
                            })
                            ->copyable()
                            ->placeholder('—')
                            ->columnSpanFull()
                            ->visible(function (OperationRun $record): bool {
                                $context = is_array($record->context) ? $record->context : [];
                                $value = data_get($context, 'baseline_compare.resume_token');

                                return is_string($value) && $value !== '';
                            }),
                        ViewEntry::make('baseline_compare_evidence_capture')
                            ->label('Evidence capture')
                            ->view('filament.infolists.entries.snapshot-json')
                            ->state(function (OperationRun $record): array {
                                $context = is_array($record->context) ? $record->context : [];
                                $value = data_get($context, 'baseline_compare.evidence_capture');

                                return is_array($value) ? $value : [];
                            })
                            ->columnSpanFull(),
                        ViewEntry::make('baseline_compare_evidence_gaps')
                            ->label('Evidence gaps')
                            ->view('filament.infolists.entries.snapshot-json')
                            ->state(function (OperationRun $record): array {
                                $context = is_array($record->context) ? $record->context : [];
                                $value = data_get($context, 'baseline_compare.evidence_gaps');

                                return is_array($value) ? $value : [];
                            })
                            ->columnSpanFull(),
                    ])
                    ->visible(fn (OperationRun $record): bool => (string) $record->type === 'baseline_compare')
                    ->columns(2)
                    ->columnSpanFull(),

                Section::make('Baseline capture evidence')
                    ->schema([
                        TextEntry::make('baseline_capture_subjects_total')
                            ->label('Subjects total')
                            ->getStateUsing(function (OperationRun $record): ?int {
                                $context = is_array($record->context) ? $record->context : [];
                                $value = data_get($context, 'baseline_capture.subjects_total');

                                return is_numeric($value) ? (int) $value : null;
                            })
                            ->placeholder('—'),
                        TextEntry::make('baseline_capture_gap_count')
                            ->label('Gaps')
                            ->getStateUsing(function (OperationRun $record): ?int {
                                $context = is_array($record->context) ? $record->context : [];
                                $value = data_get($context, 'baseline_capture.gaps.count');

                                return is_numeric($value) ? (int) $value : null;
                            })
                            ->placeholder('—'),
                        TextEntry::make('baseline_capture_resume_token')
                            ->label('Resume token')
                            ->getStateUsing(function (OperationRun $record): ?string {
                                $context = is_array($record->context) ? $record->context : [];
                                $value = data_get($context, 'baseline_capture.resume_token');

                                return is_string($value) && $value !== '' ? $value : null;
                            })
                            ->copyable()
                            ->placeholder('—')
                            ->columnSpanFull()
                            ->visible(function (OperationRun $record): bool {
                                $context = is_array($record->context) ? $record->context : [];
                                $value = data_get($context, 'baseline_capture.resume_token');

                                return is_string($value) && $value !== '';
                            }),
                        ViewEntry::make('baseline_capture_evidence_capture')
                            ->label('Evidence capture')
                            ->view('filament.infolists.entries.snapshot-json')
                            ->state(function (OperationRun $record): array {
                                $context = is_array($record->context) ? $record->context : [];
                                $value = data_get($context, 'baseline_capture.evidence_capture');

                                return is_array($value) ? $value : [];
                            })
                            ->columnSpanFull(),
                        ViewEntry::make('baseline_capture_gaps')
                            ->label('Gaps')
                            ->view('filament.infolists.entries.snapshot-json')
                            ->state(function (OperationRun $record): array {
                                $context = is_array($record->context) ? $record->context : [];
                                $value = data_get($context, 'baseline_capture.gaps');

                                return is_array($value) ? $value : [];
                            })
                            ->columnSpanFull(),
                    ])
                    ->visible(fn (OperationRun $record): bool => (string) $record->type === 'baseline_capture')
                    ->columns(2)
                    ->columnSpanFull(),

                Section::make('Verification report')
                    ->schema([
                        ViewEntry::make('verification_report')
                            ->label('')
                            ->view('filament.components.verification-report-viewer')
                            ->state(fn (OperationRun $record): ?array => VerificationReportViewer::report($record))
                            ->viewData(function (OperationRun $record): array {
                                $report = VerificationReportViewer::report($record);
                                $fingerprint = is_array($report) ? VerificationReportViewer::fingerprint($report) : null;

                                $changeIndicator = VerificationReportChangeIndicator::forRun($record);

                                $previousRunUrl = null;

                                if ($changeIndicator !== null) {
                                    $tenant = Filament::getTenant();

                                    $previousRunUrl = $tenant instanceof Tenant
                                        ? OperationRunLinks::view($changeIndicator['previous_report_id'], $tenant)
                                        : OperationRunLinks::tenantlessView($changeIndicator['previous_report_id']);
                                }

                                $acknowledgements = VerificationCheckAcknowledgement::query()
                                    ->where('tenant_id', (int) ($record->tenant_id ?? 0))
                                    ->where('workspace_id', (int) ($record->workspace_id ?? 0))
                                    ->where('operation_run_id', (int) $record->getKey())
                                    ->with('acknowledgedByUser')
                                    ->get()
                                    ->mapWithKeys(static function (VerificationCheckAcknowledgement $ack): array {
                                        $user = $ack->acknowledgedByUser;

                                        return [
                                            (string) $ack->check_key => [
                                                'check_key' => (string) $ack->check_key,
                                                'ack_reason' => (string) $ack->ack_reason,
                                                'acknowledged_at' => $ack->acknowledged_at?->toJSON(),
                                                'expires_at' => $ack->expires_at?->toJSON(),
                                                'acknowledged_by' => $user instanceof User
                                                    ? [
                                                        'id' => (int) $user->getKey(),
                                                        'name' => (string) $user->name,
                                                    ]
                                                    : null,
                                            ],
                                        ];
                                    })
                                    ->all();

                                return [
                                    'run' => [
                                        'id' => (int) $record->getKey(),
                                        'type' => (string) $record->type,
                                        'status' => (string) $record->status,
                                        'outcome' => (string) $record->outcome,
                                        'started_at' => $record->started_at?->toJSON(),
                                        'completed_at' => $record->completed_at?->toJSON(),
                                    ],
                                    'fingerprint' => $fingerprint,
                                    'changeIndicator' => $changeIndicator,
                                    'previousRunUrl' => $previousRunUrl,
                                    'acknowledgements' => $acknowledgements,
                                    'redactionNotes' => VerificationReportViewer::redactionNotes($report),
                                ];
                            })
                            ->columnSpanFull(),
                    ])
                    ->visible(fn (OperationRun $record): bool => VerificationReportViewer::shouldRenderForRun($record))
                    ->columnSpanFull(),

                Section::make('Integrity')
                    ->schema([
                        TextEntry::make('redaction_integrity_note')
                            ->label('')
                            ->getStateUsing(fn (OperationRun $record): ?string => RedactionIntegrity::noteForRun($record))
                            ->columnSpanFull(),
                    ])
                    ->visible(fn (OperationRun $record): bool => RedactionIntegrity::noteForRun($record) !== null)
                    ->columnSpanFull(),

                Section::make('Context')
                    ->schema([
                        ViewEntry::make('context')
                            ->label('')
                            ->view('filament.infolists.entries.snapshot-json')
                            ->state(function (OperationRun $record): array {
                                $context = $record->context ?? [];
                                $context = is_array($context) ? $context : [];

                                if (array_key_exists('verification_report', $context)) {
                                    $context['verification_report'] = [
                                        'redacted' => true,
                                        'note' => 'Rendered in the Verification report section.',
                                    ];
                                }

                                return $context;
                            })
                            ->columnSpanFull(),
                    ])
                    ->columnSpanFull(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('created_at', 'desc')
            ->paginated(TablePaginationProfiles::resource())
            ->persistFiltersInSession()
            ->persistSearchInSession()
            ->persistSortInSession()
            ->columns([
                Tables\Columns\TextColumn::make('status')
                    ->badge()
                    ->formatStateUsing(BadgeRenderer::label(BadgeDomain::OperationRunStatus))
                    ->color(BadgeRenderer::color(BadgeDomain::OperationRunStatus))
                    ->icon(BadgeRenderer::icon(BadgeDomain::OperationRunStatus))
                    ->iconColor(BadgeRenderer::iconColor(BadgeDomain::OperationRunStatus)),
                Tables\Columns\TextColumn::make('type')
                    ->label('Operation')
                    ->formatStateUsing(fn (?string $state): string => OperationCatalog::label((string) $state))
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('initiator_name')
                    ->label('Initiator')
                    ->searchable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Started')
                    ->since()
                    ->sortable(),
                Tables\Columns\TextColumn::make('duration')
                    ->getStateUsing(function (OperationRun $record): string {
                        if ($record->started_at && $record->completed_at) {
                            return $record->completed_at->diffForHumans($record->started_at, true);
                        }

                        return '—';
                    }),
                Tables\Columns\TextColumn::make('outcome')
                    ->badge()
                    ->formatStateUsing(BadgeRenderer::label(BadgeDomain::OperationRunOutcome))
                    ->color(BadgeRenderer::color(BadgeDomain::OperationRunOutcome))
                    ->icon(BadgeRenderer::icon(BadgeDomain::OperationRunOutcome))
                    ->iconColor(BadgeRenderer::iconColor(BadgeDomain::OperationRunOutcome)),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('tenant_id')
                    ->label('Tenant')
                    ->options(function (): array {
                        $activeTenant = app(OperateHubShell::class)->activeEntitledTenant(request());

                        if ($activeTenant instanceof Tenant) {
                            return [
                                (string) $activeTenant->getKey() => $activeTenant->getFilamentName(),
                            ];
                        }

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

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

                        return collect($user->getTenants(Filament::getCurrentOrDefaultPanel()))
                            ->mapWithKeys(static fn (Tenant $tenant): array => [
                                (string) $tenant->getKey() => $tenant->getFilamentName(),
                            ])
                            ->all();
                    })
                    ->default(function (): ?string {
                        $activeTenant = app(OperateHubShell::class)->activeEntitledTenant(request());

                        if (! $activeTenant instanceof Tenant) {
                            return null;
                        }

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

                        if ($workspaceId === null || (int) $activeTenant->workspace_id !== (int) $workspaceId) {
                            return null;
                        }

                        return (string) $activeTenant->getKey();
                    })
                    ->searchable(),
                Tables\Filters\SelectFilter::make('type')
                    ->options(function (): array {
                        $workspaceId = app(WorkspaceContext::class)->currentWorkspaceId();

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

                        $types = OperationRun::query()
                            ->where('workspace_id', (int) $workspaceId)
                            ->select('type')
                            ->distinct()
                            ->orderBy('type')
                            ->pluck('type', 'type')
                            ->all();

                        return FilterOptionCatalog::operationTypes(array_keys($types));
                    }),
                Tables\Filters\SelectFilter::make('status')
                    ->options([
                        OperationRunStatus::Queued->value => 'Queued',
                        OperationRunStatus::Running->value => 'Running',
                        OperationRunStatus::Completed->value => 'Completed',
                    ]),
                Tables\Filters\SelectFilter::make('outcome')
                    ->options(OperationRunOutcome::uiLabels(includeReserved: false)),
                Tables\Filters\SelectFilter::make('initiator_name')
                    ->label('Initiator')
                    ->options(function (): array {
                        $workspaceId = app(WorkspaceContext::class)->currentWorkspaceId();

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

                        $tenant = Filament::getTenant();
                        $tenantId = $tenant instanceof Tenant && (int) $tenant->workspace_id === (int) $workspaceId
                            ? (int) $tenant->getKey()
                            : null;

                        return OperationRun::query()
                            ->where('workspace_id', (int) $workspaceId)
                            ->when($tenantId, fn (Builder $query): Builder => $query->where('tenant_id', $tenantId))
                            ->whereNotNull('initiator_name')
                            ->select('initiator_name')
                            ->distinct()
                            ->orderBy('initiator_name')
                            ->pluck('initiator_name', 'initiator_name')
                            ->all();
                    })
                    ->searchable(),
                FilterPresets::dateRange('created_at', 'Created', 'created_at', [
                    'from' => now()->subDays(30)->toDateString(),
                    'until' => now()->toDateString(),
                ]),
            ])
            ->actions([
                Actions\ViewAction::make()
                    ->label('View run')
                    ->url(fn (OperationRun $record): string => OperationRunLinks::tenantlessView($record)),
            ])
            ->bulkActions([])
            ->emptyStateHeading('No operation runs found')
            ->emptyStateDescription('Queued, running, and completed operations will appear here when work is triggered in this scope.')
            ->emptyStateIcon('heroicon-o-queue-list');
    }

    public static function getPages(): array
    {
        return [];
    }

    private static function targetScopeDisplay(OperationRun $record): ?string
    {
        $context = is_array($record->context) ? $record->context : [];

        $targetScope = $context['target_scope'] ?? null;
        if (! is_array($targetScope)) {
            return null;
        }

        $entraTenantName = $targetScope['entra_tenant_name'] ?? null;
        $entraTenantId = $targetScope['entra_tenant_id'] ?? null;
        $directoryContextId = $targetScope['directory_context_id'] ?? null;

        $entraTenantName = is_string($entraTenantName) ? trim($entraTenantName) : null;
        $entraTenantId = is_string($entraTenantId) ? trim($entraTenantId) : null;

        $directoryContextId = match (true) {
            is_string($directoryContextId) => trim($directoryContextId),
            is_int($directoryContextId) => (string) $directoryContextId,
            default => null,
        };

        $entra = null;

        if ($entraTenantName !== null && $entraTenantName !== '') {
            $entra = $entraTenantId ? "{$entraTenantName} ({$entraTenantId})" : $entraTenantName;
        } elseif ($entraTenantId !== null && $entraTenantId !== '') {
            $entra = $entraTenantId;
        }

        $parts = array_values(array_filter([
            $entra,
            $directoryContextId ? "directory_context_id: {$directoryContextId}" : null,
        ], fn (?string $value): bool => $value !== null && $value !== ''));

        return $parts !== [] ? implode(' · ', $parts) : null;
    }
}
