<?php

namespace App\Filament\Resources;

use App\Filament\Concerns\ResolvesPanelTenantContext;
use App\Filament\Resources\ProviderConnectionResource\Pages;
use App\Jobs\ProviderComplianceSnapshotJob;
use App\Jobs\ProviderInventorySyncJob;
use App\Models\ManagedEnvironment;
use App\Models\OperationRun;
use App\Models\ProviderConnection;
use App\Models\User;
use App\Services\Auth\CapabilityResolver;
use App\Services\Auth\ManagedEnvironmentAccessScopeResolver;
use App\Services\Intune\AuditLogger;
use App\Services\Providers\ProviderConnectionMutationService;
use App\Services\Providers\ProviderOperationStartGate;
use App\Services\Verification\StartVerification;
use App\Support\Auth\Capabilities;
use App\Support\Badges\BadgeDomain;
use App\Support\Badges\BadgeRenderer;
use App\Support\Filament\TablePaginationProfiles;
use App\Support\ManagedEnvironmentLinks;
use App\Support\Navigation\WorkspaceHubEnvironmentFilter;
use App\Support\OperationRunLinks;
use App\Support\OperationRunType;
use App\Support\OpsUx\OpsUxBrowserEvents;
use App\Support\OpsUx\ProviderOperationStartResultPresenter;
use App\Support\Providers\ProviderConnectionType;
use App\Support\Providers\ProviderReasonCodes;
use App\Support\Providers\ProviderVerificationStatus;
use App\Support\Providers\TargetScope\ProviderConnectionSurfaceSummary;
use App\Support\Providers\TargetScope\ProviderConnectionTargetScopeNormalizer;
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\Workspaces\WorkspaceContext;
use BackedEnum;
use Filament\Actions;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Infolists;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use InvalidArgumentException;
use UnitEnum;

class ProviderConnectionResource extends Resource
{
    use ResolvesPanelTenantContext;

    protected static bool $isDiscovered = false;

    protected static bool $isScopedToTenant = false;

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

    protected static ?string $slug = 'provider-connections';

    protected static bool $isGloballySearchable = false;

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

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

    protected static ?string $navigationLabel = 'Provider Connections';

    protected static ?string $recordTitleAttribute = 'display_name';

    public static function getNavigationParentItem(): ?string
    {
        return 'Integrations';
    }

    public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
    {
        return ActionSurfaceDeclaration::forResource(ActionSurfaceProfile::CrudListAndView)
            ->satisfy(ActionSurfaceSlot::ListHeader, 'Header actions include capability-gated create.')
            ->satisfy(ActionSurfaceSlot::InspectAffordance, ActionSurfaceInspectAffordance::ClickableRow->value)
            ->satisfy(ActionSurfaceSlot::ListRowMoreMenu, 'Edit and provider operations are grouped under "More" while clickable-row view remains primary.')
            ->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'Provider connections intentionally omit bulk actions.')
            ->satisfy(ActionSurfaceSlot::ListEmptyState, 'List page defines empty-state guidance and CTA.')
            ->satisfy(ActionSurfaceSlot::DetailHeader, 'View page keeps one primary consent CTA while shared connection actions remain grouped under "More".');
    }

    public static function canCreate(): bool
    {
        $tenant = static::resolveTenantForCreate();
        $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::PROVIDER_MANAGE);
    }

    protected static function hasTenantCapability(string $capability): bool
    {
        $tenant = static::resolveScopedTenant();
        $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, $capability);
    }

    protected static function resolveScopedTenant(): ?ManagedEnvironment
    {
        $tenantExternalId = static::resolveRequestedTenantExternalId();

        if (is_string($tenantExternalId) && $tenantExternalId !== '') {
            return static::resolveTenantByExternalId($tenantExternalId);
        }

        $routeTenant = request()->route('tenant');

        if ($routeTenant instanceof ManagedEnvironment) {
            return $routeTenant;
        }

        if (is_string($routeTenant) && $routeTenant !== '') {
            return ManagedEnvironment::query()
                ->where('slug', $routeTenant)
                ->first();
        }

        $recordTenant = static::resolveTenantFromRouteRecord();

        if ($recordTenant instanceof ManagedEnvironment) {
            return $recordTenant;
        }

        $contextTenantExternalId = static::resolveContextTenantExternalId();

        if (is_string($contextTenantExternalId) && $contextTenantExternalId !== '') {
            return static::resolveTenantByExternalId($contextTenantExternalId);
        }

        return static::resolveTenantContextForCurrentPanel();
    }

    public static function resolveTenantForRecord(?ProviderConnection $record = null): ?ManagedEnvironment
    {
        if ($record instanceof ProviderConnection) {
            $tenant = $record->tenant;

            if (! $tenant instanceof ManagedEnvironment && is_numeric($record->managed_environment_id)) {
                $tenant = ManagedEnvironment::query()->whereKey((int) $record->managed_environment_id)->first();
            }

            if ($tenant instanceof ManagedEnvironment) {
                return $tenant;
            }
        }

        return static::resolveScopedTenant();
    }

    public static function resolveRequestedTenantExternalId(): ?string
    {
        $environment = static::resolveRequestedEnvironment();

        if ($environment instanceof ManagedEnvironment) {
            return (string) $environment->slug;
        }

        return static::resolveTenantExternalIdFromLivewireRequest();
    }

    public static function resolveRequestedEnvironment(): ?ManagedEnvironment
    {
        $workspace = app(WorkspaceContext::class)->currentWorkspace(request());

        if (! $workspace instanceof \App\Models\Workspace) {
            return null;
        }

        return WorkspaceHubEnvironmentFilter::fromRequest(request(), $workspace)?->environment();
    }

    public static function resolveContextTenantExternalId(): ?string
    {
        $tenant = static::resolveTenantContextForCurrentPanel();

        if ($tenant instanceof ManagedEnvironment) {
            return (string) $tenant->slug;
        }

        return null;
    }

    public static function resolveTenantForCreate(): ?ManagedEnvironment
    {
        $tenantExternalId = static::resolveRequestedTenantExternalId();

        if (! is_string($tenantExternalId) || $tenantExternalId === '') {
            return null;
        }

        $tenant = static::resolveTenantByExternalId($tenantExternalId);
        $user = auth()->user();
        $workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());

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

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

        if (! $user->canAccessTenant($tenant)) {
            return null;
        }

        return $tenant;
    }

    private static function resolveTenantExternalIdFromLivewireRequest(): ?string
    {
        if (! request()->headers->has('x-livewire') && ! request()->headers->has('x-livewire-navigate')) {
            return null;
        }

        try {
            $url = \Livewire\Livewire::originalUrl();

            if (is_string($url) && $url !== '') {
                $externalId = static::extractTenantExternalIdFromUrl($url);

                if (is_string($externalId) && $externalId !== '') {
                    return $externalId;
                }
            }
        } catch (\Throwable) {
            // Ignore and fall back to referer.
        }

        $referer = request()->headers->get('referer');

        if (! is_string($referer) || $referer === '') {
            return null;
        }

        return static::extractTenantExternalIdFromUrl($referer);
    }

    private static function extractTenantExternalIdFromUrl(string $url): ?string
    {
        $query = parse_url($url, PHP_URL_QUERY);

        if (is_string($query) && $query !== '') {
            parse_str($query, $queryParams);

            $tenantExternalId = $queryParams['environment_id'] ?? null;

            if (is_numeric($tenantExternalId)) {
                $tenant = ManagedEnvironment::query()
                    ->whereKey((int) $tenantExternalId)
                    ->where('workspace_id', app(WorkspaceContext::class)->currentWorkspaceId(request()))
                    ->first();

                return $tenant instanceof ManagedEnvironment ? (string) $tenant->slug : null;
            }
        }

        return null;
    }

    private static function resolveTenantByExternalId(?string $externalId): ?ManagedEnvironment
    {
        if (! is_string($externalId) || $externalId === '') {
            return null;
        }

        return ManagedEnvironment::query()
            ->where('slug', $externalId)
            ->first();
    }

    private static function resolveTenantFromRouteRecord(): ?ManagedEnvironment
    {
        $record = request()->route('record');

        if ($record instanceof ProviderConnection) {
            return static::resolveTenantForRecord($record);
        }

        if (! is_numeric($record)) {
            return null;
        }

        $providerConnection = ProviderConnection::query()
            ->with('tenant')
            ->whereKey((int) $record)
            ->first();

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

        return static::resolveTenantForRecord($providerConnection);
    }

    private static function applyMembershipScope(Builder $query): Builder
    {
        $workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
        $user = auth()->user();

        if (! is_int($workspaceId)) {
            $tenant = static::resolveTenantContextForCurrentPanel();

            if ($tenant instanceof ManagedEnvironment) {
                $workspaceId = (int) $tenant->workspace_id;
            }
        }

        if (! is_int($workspaceId) || ! $user instanceof User) {
            return $query->whereRaw('1 = 0');
        }

        $query->where('provider_connections.workspace_id', $workspaceId);

        app(ManagedEnvironmentAccessScopeResolver::class)->applyWorkspaceScopeToQuery(
            query: $query,
            user: $user,
            workspaceId: $workspaceId,
            qualifiedEnvironmentColumn: 'provider_connections.managed_environment_id',
        );

        return $query;
    }

    /**
     * @return array<string, string>
     */
    private static function tenantFilterOptions(): array
    {
        $workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
        $user = auth()->user();

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

        $query = ManagedEnvironment::query()
            ->select(['managed_environments.slug', 'managed_environments.name', 'managed_environments.kind'])
            ->where('managed_environments.workspace_id', $workspaceId);

        app(ManagedEnvironmentAccessScopeResolver::class)->applyWorkspaceScopeToQuery(
            query: $query,
            user: $user,
            workspaceId: $workspaceId,
            qualifiedEnvironmentColumn: 'managed_environments.id',
        );

        return $query
            ->orderBy('managed_environments.name')
            ->get()
            ->mapWithKeys(function (ManagedEnvironment $tenant): array {
                $environment = strtoupper((string) ($tenant->environment ?? ''));
                $label = $environment !== '' ? "{$tenant->name} ({$environment})" : (string) $tenant->name;

                return [(string) $tenant->slug => $label];
            })
            ->all();
    }

    private static function sanitizeErrorMessage(?string $value): ?string
    {
        if (! is_string($value) || trim($value) === '') {
            return null;
        }

        $normalized = preg_replace('/\s+/', ' ', strip_tags($value));
        $normalized = is_string($normalized) ? trim($normalized) : '';

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

        return Str::limit($normalized, 120);
    }

    private static function providerConnectionTypeLabel(?ProviderConnection $record): string
    {
        $connectionType = $record?->connection_type;

        if ($connectionType instanceof ProviderConnectionType && $connectionType === ProviderConnectionType::Dedicated) {
            return 'Dedicated connection';
        }

        return 'Platform connection';
    }

    private static function effectiveAppId(?ProviderConnection $record): string
    {
        $effectiveAppId = $record?->effectiveAppId();

        return filled($effectiveAppId) ? (string) $effectiveAppId : 'Effective app pending review';
    }

    private static function credentialSourceLabel(?ProviderConnection $record): string
    {
        if (! $record instanceof ProviderConnection) {
            return 'Managed centrally by platform';
        }

        $effectiveApp = $record->effectiveAppMetadata();

        return match ($effectiveApp['source'] ?? null) {
            'dedicated_credential' => 'Dedicated credential',
            'review_required' => 'Legacy identity review required',
            default => 'Managed centrally by platform',
        };
    }

    private static function migrationReviewLabel(?ProviderConnection $record): string
    {
        return $record?->requiresMigrationReview() ? 'Review required' : 'Clear';
    }

    private static function migrationReviewDescription(?ProviderConnection $record): ?string
    {
        if (! $record instanceof ProviderConnection) {
            return null;
        }

        $metadata = $record->legacyIdentityMetadata();
        $source = $metadata['legacy_identity_classification_source'] ?? null;
        $result = $metadata['legacy_identity_result'] ?? null;

        if (! $record->requiresMigrationReview()) {
            return filled($source) ? sprintf('Classified via %s as %s.', $source, $result ?? 'platform') : null;
        }

        $signals = $metadata['legacy_identity_signals'] ?? [];
        $tenantClientId = $signals['tenant_client_id'] ?? null;
        $credentialClientId = $signals['credential_client_id'] ?? null;

        if (filled($tenantClientId) && filled($credentialClientId)) {
            return sprintf('Legacy tenant app %s conflicts with dedicated app %s.', $tenantClientId, $credentialClientId);
        }

        return 'Legacy app evidence conflicts with the current connection and needs explicit review.';
    }

    private static function consentStatusLabelFromState(mixed $state): string
    {
        return BadgeRenderer::spec(BadgeDomain::ProviderConsentStatus, $state)->label;
    }

    private static function lifecycleLabelFromState(mixed $state): string
    {
        return BadgeRenderer::spec(BadgeDomain::BooleanEnabled, $state)->label;
    }

    private static function verificationStatusLabelFromState(mixed $state): string
    {
        return BadgeRenderer::spec(BadgeDomain::ProviderVerificationStatus, $state)->label;
    }

    private static function targetScopeHelpText(): string
    {
        return 'The platform scope this provider connection represents. For Microsoft, use the tenant directory ID for that scope.';
    }

    private static function targetScopeSummary(?ProviderConnection $record): string
    {
        if (! $record instanceof ProviderConnection) {
            return 'Target scope is set when this connection is saved.';
        }

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

    private static function providerContextSummary(?ProviderConnection $record): ?string
    {
        if (! $record instanceof ProviderConnection) {
            return null;
        }

        try {
            return ProviderConnectionSurfaceSummary::forConnection($record)->contextualIdentityLine();
        } catch (InvalidArgumentException) {
            return null;
        }
    }

    private static function providerCapabilitySummary(?ProviderConnection $record): string
    {
        if (! $record instanceof ProviderConnection) {
            return 'Provider capabilities are evaluated after this connection is saved.';
        }

        try {
            return ProviderConnectionSurfaceSummary::forConnection($record)->providerCapabilitySummary();
        } catch (InvalidArgumentException) {
            return 'Provider capability needs review';
        }
    }

    private static function providerCapabilityStatus(?ProviderConnection $record): string
    {
        if (! $record instanceof ProviderConnection) {
            return 'unknown';
        }

        try {
            $summary = ProviderConnectionSurfaceSummary::forConnection($record)->toArray();
            $primary = is_array($summary['primary_provider_capability'] ?? null)
                ? $summary['primary_provider_capability']
                : [];

            return (string) ($primary['status'] ?? 'unknown');
        } catch (InvalidArgumentException) {
            return 'unknown';
        }
    }

    private static function providerCapabilitiesLine(?ProviderConnection $record): string
    {
        if (! $record instanceof ProviderConnection) {
            return 'Provider capabilities are evaluated after this connection is saved.';
        }

        try {
            $summary = ProviderConnectionSurfaceSummary::forConnection($record)->toArray();
            $capabilities = is_array($summary['provider_capabilities'] ?? null)
                ? $summary['provider_capabilities']
                : [];
        } catch (InvalidArgumentException) {
            $capabilities = [];
        }

        if ($capabilities === []) {
            return 'Provider capabilities not evaluated.';
        }

        return collect($capabilities)
            ->filter(fn (mixed $capability): bool => is_array($capability))
            ->map(function (array $capability): string {
                $label = (string) ($capability['label'] ?? 'Provider capability');
                $status = (string) ($capability['status'] ?? 'unknown');
                $statusLabel = BadgeRenderer::spec(BadgeDomain::ProviderCapabilityStatus, $status)->label;

                return "{$label}: {$statusLabel}";
            })
            ->implode("\n");
    }

    /**
     * @param  array<string, mixed>  $extra
     * @return array<string, mixed>
     */
    public static function targetScopeAuditMetadata(ProviderConnection $record, array $extra = []): array
    {
        try {
            return app(ProviderConnectionTargetScopeNormalizer::class)->auditMetadataForConnection($record, $extra);
        } catch (InvalidArgumentException) {
            return array_merge([
                'provider_connection_id' => (int) $record->getKey(),
                'provider' => (string) $record->provider,
                'target_scope' => [
                    'provider' => (string) $record->provider,
                    'scope_kind' => 'tenant',
                    'scope_identifier' => (string) $record->entra_tenant_id,
                    'scope_display_name' => (string) ($record->tenant?->name ?? $record->display_name ?? $record->entra_tenant_id),
                    'shared_label' => 'Target scope',
                    'shared_help_text' => static::targetScopeHelpText(),
                ],
                'provider_context' => [
                    'provider' => (string) $record->provider,
                    'details' => [],
                ],
            ], $extra);
        }
    }

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->schema([
                Section::make('Connection')
                    ->schema([
                        TextInput::make('display_name')
                            ->label('Display name')
                            ->required()
                            ->disabled(fn (): bool => ! static::hasTenantCapability(Capabilities::PROVIDER_MANAGE))
                            ->maxLength(255),
                        TextInput::make('entra_tenant_id')
                            ->label('Target scope ID')
                            ->required()
                            ->maxLength(255)
                            ->helperText(static::targetScopeHelpText())
                            ->validationAttribute('target scope ID')
                            ->disabled(fn (): bool => ! static::hasTenantCapability(Capabilities::PROVIDER_MANAGE))
                            ->rules(['uuid']),
                        Placeholder::make('target_scope_display')
                            ->label('Target scope')
                            ->content(fn (?ProviderConnection $record): string => static::targetScopeSummary($record))
                            ->visible(fn (?ProviderConnection $record): bool => $record instanceof ProviderConnection),
                        Placeholder::make('connection_type_display')
                            ->label('Connection type')
                            ->content(fn (?ProviderConnection $record): string => static::providerConnectionTypeLabel($record)),
                        Placeholder::make('platform_app_id_display')
                            ->label('Effective app ID')
                            ->content(fn (?ProviderConnection $record): string => static::effectiveAppId($record)),
                        Placeholder::make('effective_app_source_display')
                            ->label('Effective app source')
                            ->content(fn (?ProviderConnection $record): string => static::credentialSourceLabel($record)),
                        Toggle::make('is_default')
                            ->label('Default connection')
                            ->disabled(fn (): bool => ! static::hasTenantCapability(Capabilities::PROVIDER_MANAGE))
                            ->helperText('Exactly one default connection is required per tenant/provider.'),
                    ])
                    ->columns(2)
                    ->columnSpanFull(),
                Section::make('Current state')
                    ->schema([
                        Placeholder::make('is_enabled_display')
                            ->label('Lifecycle')
                            ->content(fn (?ProviderConnection $record): string => static::lifecycleLabelFromState($record?->is_enabled)),
                        Placeholder::make('consent_status_display')
                            ->label('Consent')
                            ->content(fn (?ProviderConnection $record): string => static::consentStatusLabelFromState($record?->consent_status)),
                        Placeholder::make('verification_status_display')
                            ->label('Verification')
                            ->content(fn (?ProviderConnection $record): string => static::verificationStatusLabelFromState($record?->verification_status)),
                        Placeholder::make('provider_capability_display')
                            ->label('Provider capability')
                            ->content(fn (?ProviderConnection $record): string => static::providerCapabilitySummary($record)),
                        Placeholder::make('last_health_check_at_display')
                            ->label('Last check')
                            ->content(fn (?ProviderConnection $record): string => $record?->last_health_check_at?->diffForHumans() ?? 'Never'),
                    ])
                    ->columns(2)
                    ->columnSpanFull(),
                Section::make('Diagnostics')
                    ->schema([
                        Placeholder::make('migration_review_status_display')
                            ->label('Migration review')
                            ->content(fn (?ProviderConnection $record): string => static::migrationReviewLabel($record))
                            ->hint(fn (?ProviderConnection $record): ?string => static::migrationReviewDescription($record)),
                        Placeholder::make('last_error_reason_code_display')
                            ->label('Last error reason')
                            ->content(fn (?ProviderConnection $record): string => filled($record?->last_error_reason_code) ? (string) $record->last_error_reason_code : 'n/a'),
                        Placeholder::make('last_error_message_display')
                            ->label('Last error message')
                            ->content(fn (?ProviderConnection $record): string => static::sanitizeErrorMessage($record?->last_error_message) ?? 'n/a')
                            ->columnSpanFull(),
                    ])
                    ->columns(2)
                    ->columnSpanFull(),
            ]);
    }

    public static function infolist(Schema $schema): Schema
    {
        return $schema
            ->schema([
                Section::make('Connection')
                    ->schema([
                        Infolists\Components\TextEntry::make('display_name')
                            ->label('Display name'),
                        Infolists\Components\TextEntry::make('provider')
                            ->label('Provider'),
                        Infolists\Components\TextEntry::make('target_scope')
                            ->label('Target scope')
                            ->state(fn (ProviderConnection $record): string => static::targetScopeSummary($record))
                            ->copyable(),
                        Infolists\Components\TextEntry::make('connection_type')
                            ->label('Connection type')
                            ->formatStateUsing(fn (?ProviderConnectionType $state): string => $state === ProviderConnectionType::Dedicated
                                ? 'Dedicated connection'
                                : 'Platform connection'),
                        Infolists\Components\TextEntry::make('effective_app_id')
                            ->label('Effective app ID')
                            ->state(fn (ProviderConnection $record): string => static::effectiveAppId($record))
                            ->copyable(),
                        Infolists\Components\TextEntry::make('effective_app_source')
                            ->label('Effective app source')
                            ->state(fn (ProviderConnection $record): string => static::credentialSourceLabel($record)),
                    ])
                    ->columns(2),
                Section::make('Current state')
                    ->schema([
                        Infolists\Components\TextEntry::make('is_enabled')
                            ->label('Lifecycle')
                            ->badge()
                            ->formatStateUsing(fn ($state): string => static::lifecycleLabelFromState($state))
                            ->color(BadgeRenderer::color(BadgeDomain::BooleanEnabled))
                            ->icon(BadgeRenderer::icon(BadgeDomain::BooleanEnabled))
                            ->iconColor(BadgeRenderer::iconColor(BadgeDomain::BooleanEnabled)),
                        Infolists\Components\TextEntry::make('consent_status')
                            ->label('Consent')
                            ->badge()
                            ->formatStateUsing(fn ($state): string => static::consentStatusLabelFromState($state))
                            ->color(BadgeRenderer::color(BadgeDomain::ProviderConsentStatus))
                            ->icon(BadgeRenderer::icon(BadgeDomain::ProviderConsentStatus))
                            ->iconColor(BadgeRenderer::iconColor(BadgeDomain::ProviderConsentStatus)),
                        Infolists\Components\TextEntry::make('verification_status')
                            ->label('Verification')
                            ->badge()
                            ->formatStateUsing(fn ($state): string => static::verificationStatusLabelFromState($state))
                            ->color(BadgeRenderer::color(BadgeDomain::ProviderVerificationStatus))
                            ->icon(BadgeRenderer::icon(BadgeDomain::ProviderVerificationStatus))
                            ->iconColor(BadgeRenderer::iconColor(BadgeDomain::ProviderVerificationStatus)),
                        Infolists\Components\TextEntry::make('provider_capability')
                            ->label('Provider capability')
                            ->state(fn (ProviderConnection $record): string => static::providerCapabilityStatus($record))
                            ->badge()
                            ->formatStateUsing(BadgeRenderer::label(BadgeDomain::ProviderCapabilityStatus))
                            ->color(BadgeRenderer::color(BadgeDomain::ProviderCapabilityStatus))
                            ->icon(BadgeRenderer::icon(BadgeDomain::ProviderCapabilityStatus))
                            ->iconColor(BadgeRenderer::iconColor(BadgeDomain::ProviderCapabilityStatus))
                            ->helperText(fn (ProviderConnection $record): string => static::providerCapabilitySummary($record)),
                        Infolists\Components\TextEntry::make('provider_capability_summary')
                            ->label('Capability summary')
                            ->state(fn (ProviderConnection $record): string => static::providerCapabilitySummary($record))
                            ->columnSpanFull(),
                        Infolists\Components\TextEntry::make('provider_capabilities')
                            ->label('Capability detail')
                            ->state(fn (ProviderConnection $record): string => static::providerCapabilitiesLine($record))
                            ->listWithLineBreaks()
                            ->columnSpanFull(),
                        Infolists\Components\TextEntry::make('last_health_check_at')
                            ->label('Last check')
                            ->since(),
                    ])
                    ->columns(2),
                Section::make('Diagnostics')
                    ->schema([
                        Infolists\Components\TextEntry::make('migration_review_required')
                            ->label('Migration review')
                            ->formatStateUsing(fn (ProviderConnection $record): string => static::migrationReviewLabel($record))
                            ->tooltip(fn (ProviderConnection $record): ?string => static::migrationReviewDescription($record)),
                        Infolists\Components\TextEntry::make('provider_context')
                            ->label('Provider context')
                            ->state(fn (ProviderConnection $record): ?string => static::providerContextSummary($record))
                            ->placeholder('n/a')
                            ->columnSpanFull(),
                        Infolists\Components\TextEntry::make('last_error_reason_code')
                            ->label('Last error reason')
                            ->placeholder('n/a'),
                        Infolists\Components\TextEntry::make('last_error_message')
                            ->label('Last error message')
                            ->formatStateUsing(fn (?string $state): ?string => static::sanitizeErrorMessage($state))
                            ->placeholder('n/a')
                            ->columnSpanFull(),
                    ])
                    ->columns(2),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->modifyQueryUsing(function (Builder $query): Builder {
                $query->with(['tenant', 'credential']);

                $tenantExternalId = static::resolveRequestedTenantExternalId();

                if (! is_string($tenantExternalId) || $tenantExternalId === '') {
                    return $query;
                }

                return $query->whereHas('tenant', function (Builder $tenantQuery) use ($tenantExternalId): void {
                    $tenantQuery->where('slug', $tenantExternalId);
                });
            })
            ->defaultSort('display_name')
            ->paginated(TablePaginationProfiles::resource())
            ->persistFiltersInSession()
            ->persistSearchInSession()
            ->persistSortInSession()
            ->recordUrl(fn (ProviderConnection $record): string => static::getUrl('view', ['record' => $record]))
            ->columns([
                Tables\Columns\TextColumn::make('tenant.name')
                    ->label('Environment')
                    ->description(function (ProviderConnection $record): ?string {
                        $environment = $record->tenant?->environment;

                        if (! is_string($environment) || trim($environment) === '') {
                            return null;
                        }

                        return strtoupper($environment);
                    })
                    ->url(function (ProviderConnection $record): ?string {
                        $tenant = static::resolveTenantForRecord($record);

                        if (! $tenant instanceof ManagedEnvironment) {
                            return null;
                        }

                        return ManagedEnvironmentLinks::viewUrl($tenant);
                    }),
                Tables\Columns\TextColumn::make('display_name')->label('Name')->searchable()->sortable(),
                Tables\Columns\TextColumn::make('provider')
                    ->label('Provider')
                    ->formatStateUsing(fn (?string $state): string => Str::headline((string) $state)),
                Tables\Columns\TextColumn::make('target_scope')
                    ->label('Target scope')
                    ->state(fn (ProviderConnection $record): string => static::targetScopeSummary($record))
                    ->copyable(),
                Tables\Columns\TextColumn::make('entra_tenant_id')->label('Microsoft tenant ID')->copyable()->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\IconColumn::make('is_default')->label('Default')->boolean()->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('connection_type')
                    ->label('Connection type')
                    ->badge()
                    ->formatStateUsing(fn (?ProviderConnectionType $state): string => $state === ProviderConnectionType::Dedicated
                        ? 'Dedicated'
                        : 'Platform')
                    ->color(fn (?ProviderConnectionType $state): string => $state === ProviderConnectionType::Dedicated ? 'info' : 'gray'),
                Tables\Columns\TextColumn::make('is_enabled')
                    ->label('Lifecycle')
                    ->badge()
                    ->formatStateUsing(BadgeRenderer::label(BadgeDomain::BooleanEnabled))
                    ->color(BadgeRenderer::color(BadgeDomain::BooleanEnabled))
                    ->icon(BadgeRenderer::icon(BadgeDomain::BooleanEnabled))
                    ->iconColor(BadgeRenderer::iconColor(BadgeDomain::BooleanEnabled)),
                Tables\Columns\TextColumn::make('consent_status')
                    ->label('Consent')
                    ->badge()
                    ->formatStateUsing(BadgeRenderer::label(BadgeDomain::ProviderConsentStatus))
                    ->color(BadgeRenderer::color(BadgeDomain::ProviderConsentStatus))
                    ->icon(BadgeRenderer::icon(BadgeDomain::ProviderConsentStatus))
                    ->iconColor(BadgeRenderer::iconColor(BadgeDomain::ProviderConsentStatus)),
                Tables\Columns\TextColumn::make('verification_status')
                    ->label('Verification')
                    ->badge()
                    ->formatStateUsing(BadgeRenderer::label(BadgeDomain::ProviderVerificationStatus))
                    ->color(BadgeRenderer::color(BadgeDomain::ProviderVerificationStatus))
                    ->icon(BadgeRenderer::icon(BadgeDomain::ProviderVerificationStatus))
                    ->iconColor(BadgeRenderer::iconColor(BadgeDomain::ProviderVerificationStatus)),
                Tables\Columns\TextColumn::make('provider_capability')
                    ->label('Provider capability')
                    ->state(fn (ProviderConnection $record): string => static::providerCapabilityStatus($record))
                    ->badge()
                    ->formatStateUsing(BadgeRenderer::label(BadgeDomain::ProviderCapabilityStatus))
                    ->color(BadgeRenderer::color(BadgeDomain::ProviderCapabilityStatus))
                    ->icon(BadgeRenderer::icon(BadgeDomain::ProviderCapabilityStatus))
                    ->iconColor(BadgeRenderer::iconColor(BadgeDomain::ProviderCapabilityStatus))
                    ->description(fn (ProviderConnection $record): string => static::providerCapabilitySummary($record))
                    ->toggleable(),
                Tables\Columns\TextColumn::make('migration_review_required')
                    ->label('Migration review')
                    ->badge()
                    ->formatStateUsing(fn (bool $state): string => $state ? 'Review required' : 'Clear')
                    ->color(fn (bool $state): string => $state ? 'warning' : 'success')
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('last_health_check_at')
                    ->label('Last check')
                    ->since()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('last_error_reason_code')
                    ->label('Last error reason')
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('last_error_message')
                    ->label('Last error message')
                    ->formatStateUsing(fn (?string $state): ?string => static::sanitizeErrorMessage($state))
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                SelectFilter::make('tenant')
                    ->label('Environment')
                    ->default(static::resolveRequestedTenantExternalId())
                    ->options(static::tenantFilterOptions())
                    ->query(function (Builder $query, array $data): Builder {
                        $value = $data['value'] ?? null;

                        if (! is_string($value) || $value === '') {
                            return $query;
                        }

                        return $query->whereHas('tenant', function (Builder $tenantQuery) use ($value): void {
                            $tenantQuery->where('slug', $value);
                        });
                    }),
                SelectFilter::make('provider')
                    ->label('Provider')
                    ->options([
                        'microsoft' => 'Microsoft',
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        $value = $data['value'] ?? null;

                        if (! is_string($value) || $value === '') {
                            return $query;
                        }

                        return $query->where('provider_connections.provider', $value);
                    }),
                SelectFilter::make('consent_status')
                    ->label('Consent')
                    ->options([
                        'unknown' => 'Unknown',
                        'required' => 'Required',
                        'granted' => 'Granted',
                        'failed' => 'Failed',
                        'revoked' => 'Revoked',
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        $value = $data['value'] ?? null;

                        if (! is_string($value) || $value === '') {
                            return $query;
                        }

                        return $query->where('provider_connections.consent_status', $value);
                    }),
                SelectFilter::make('verification_status')
                    ->label('Verification')
                    ->options([
                        'unknown' => 'Unknown',
                        'pending' => 'Pending',
                        'healthy' => 'Healthy',
                        'degraded' => 'Degraded',
                        'blocked' => 'Blocked',
                        'error' => 'Error',
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        $value = $data['value'] ?? null;

                        if (! is_string($value) || $value === '') {
                            return $query;
                        }

                        return $query->where('provider_connections.verification_status', $value);
                    }),
                SelectFilter::make('is_enabled')
                    ->label('Lifecycle')
                    ->options([
                        'enabled' => 'Enabled',
                        'disabled' => 'Disabled',
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        $value = $data['value'] ?? null;

                        if (! is_string($value) || $value === '') {
                            return $query;
                        }

                        return $query->where('provider_connections.is_enabled', $value === 'enabled');
                    }),
                Filter::make('default_only')
                    ->label('Default only')
                    ->query(fn (Builder $query): Builder => $query->where('provider_connections.is_default', true)),
            ])
            ->actions([
                Actions\ActionGroup::make([
                    static::makeEditNavigationAction(),
                    static::makeCheckConnectionAction(),
                    static::makeInventorySyncAction(),
                    static::makeComplianceSnapshotAction(),
                    static::makeSetDefaultAction(),
                    static::makeEnableDedicatedOverrideAction(
                        source: 'provider_connection.resource_table',
                        modalDescription: 'Dedicated credentials are stored encrypted and reset consent to the dedicated app registration.',
                    ),
                    static::makeRotateDedicatedCredentialAction(),
                    static::makeDeleteDedicatedCredentialAction(),
                    static::makeRevertToPlatformAction(source: 'provider_connection.resource_table'),
                    static::makeEnableConnectionAction(),
                    static::makeDisableConnectionAction(),
                ])
                    ->label('More')
                    ->icon('heroicon-o-ellipsis-vertical')
                    ->color('gray'),
            ])
            ->bulkActions([]);
    }

    public static function makeEditNavigationAction(): Actions\Action
    {
        return UiEnforcement::forAction(
            Actions\Action::make('edit')
                ->label('Edit')
                ->icon('heroicon-o-pencil-square')
                ->url(fn (ProviderConnection $record): string => static::getUrl('edit', ['record' => $record], tenant: static::resolveTenantForRecord($record)))
        )
            ->requireCapability(Capabilities::PROVIDER_MANAGE)
            ->apply();
    }

    public static function makeCheckConnectionAction(): Actions\Action
    {
        return UiEnforcement::forAction(
            Actions\Action::make('check_connection')
                ->label('Check connection')
                ->icon('heroicon-o-check-badge')
                ->color('success')
                ->visible(fn (ProviderConnection $record): bool => static::recordAllowsProviderExecution($record))
                ->action(function (ProviderConnection $record, StartVerification $verification, $livewire = null): void {
                    static::handleCheckConnectionAction($record, $verification, $livewire);
                })
        )
            ->preserveVisibility()
            ->requireCapability(Capabilities::PROVIDER_RUN)
            ->apply();
    }

    public static function makeInventorySyncAction(): Actions\Action
    {
        return UiEnforcement::forAction(
            Actions\Action::make('inventory_sync')
                ->label('Inventory sync')
                ->icon('heroicon-o-arrow-path')
                ->color('info')
                ->visible(fn (ProviderConnection $record): bool => static::recordAllowsProviderExecution($record))
                ->action(function (ProviderConnection $record, ProviderOperationStartGate $gate, $livewire = null): void {
                    static::handleProviderOperationAction(
                        record: $record,
                        gate: $gate,
                        operationType: OperationRunType::InventorySync->value,
                        blockedTitle: 'Inventory sync blocked',
                        dispatcher: function (ManagedEnvironment $tenant, User $user, ProviderConnection $connection, OperationRun $operationRun): void {
                            ProviderInventorySyncJob::dispatch(
                                tenantId: (int) $tenant->getKey(),
                                userId: (int) $user->getKey(),
                                providerConnectionId: (int) $connection->getKey(),
                                operationRun: $operationRun,
                            );
                        },
                        livewire: $livewire,
                    );
                })
        )
            ->preserveVisibility()
            ->requireCapability(Capabilities::PROVIDER_RUN)
            ->apply();
    }

    public static function makeComplianceSnapshotAction(): Actions\Action
    {
        return UiEnforcement::forAction(
            Actions\Action::make('compliance_snapshot')
                ->label('Compliance snapshot')
                ->icon('heroicon-o-shield-check')
                ->color('info')
                ->visible(fn (ProviderConnection $record): bool => static::recordAllowsProviderExecution($record))
                ->action(function (ProviderConnection $record, ProviderOperationStartGate $gate, $livewire = null): void {
                    static::handleProviderOperationAction(
                        record: $record,
                        gate: $gate,
                        operationType: 'compliance.snapshot',
                        blockedTitle: 'Compliance snapshot blocked',
                        dispatcher: function (ManagedEnvironment $tenant, User $user, ProviderConnection $connection, OperationRun $operationRun): void {
                            ProviderComplianceSnapshotJob::dispatch(
                                tenantId: (int) $tenant->getKey(),
                                userId: (int) $user->getKey(),
                                providerConnectionId: (int) $connection->getKey(),
                                operationRun: $operationRun,
                            );
                        },
                        livewire: $livewire,
                    );
                })
        )
            ->preserveVisibility()
            ->requireCapability(Capabilities::PROVIDER_RUN)
            ->apply();
    }

    public static function makeSetDefaultAction(): Actions\Action
    {
        return UiEnforcement::forAction(
            Actions\Action::make('set_default')
                ->label('Set as default')
                ->icon('heroicon-o-star')
                ->color('primary')
                ->requiresConfirmation()
                ->visible(fn (ProviderConnection $record): bool => (bool) $record->is_enabled && ! $record->is_default)
                ->action(function (ProviderConnection $record, AuditLogger $auditLogger): void {
                    $tenant = static::resolveTenantForRecord($record);

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

                    $record->makeDefault();

                    $user = auth()->user();
                    $actorId = $user instanceof User ? (int) $user->getKey() : null;
                    $actorEmail = $user instanceof User ? $user->email : null;
                    $actorName = $user instanceof User ? $user->name : null;

                    $auditLogger->log(
                        tenant: $tenant,
                        action: 'provider_connection.default_set',
                        context: [
                            'metadata' => static::targetScopeAuditMetadata($record),
                        ],
                        actorId: $actorId,
                        actorEmail: $actorEmail,
                        actorName: $actorName,
                        resourceType: 'provider_connection',
                        resourceId: (string) $record->getKey(),
                        status: 'success',
                    );

                    Notification::make()
                        ->title('Default connection updated')
                        ->success()
                        ->send();
                })
        )
            ->preserveVisibility()
            ->requireCapability(Capabilities::PROVIDER_MANAGE)
            ->apply();
    }

    public static function makeEnableDedicatedOverrideAction(string $source, ?string $modalDescription = null): Actions\Action
    {
        $action = Actions\Action::make('enable_dedicated_override')
            ->label('Enable dedicated override')
            ->icon('heroicon-o-key')
            ->color('primary')
            ->requiresConfirmation()
            ->visible(fn (ProviderConnection $record): bool => $record->connection_type !== ProviderConnectionType::Dedicated)
            ->form([
                TextInput::make('client_id')
                    ->label('Dedicated app (client) ID')
                    ->required()
                    ->maxLength(255),
                TextInput::make('client_secret')
                    ->label('Dedicated client secret')
                    ->password()
                    ->required()
                    ->maxLength(255),
            ])
            ->action(function (array $data, ProviderConnection $record, ProviderConnectionMutationService $mutations, AuditLogger $auditLogger) use ($source): void {
                $tenant = static::resolveTenantForRecord($record);

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

                $mutations->enableDedicatedOverride(
                    connection: $record,
                    clientId: (string) $data['client_id'],
                    clientSecret: (string) $data['client_secret'],
                );

                $user = auth()->user();
                $actorId = $user instanceof User ? (int) $user->getKey() : null;
                $actorEmail = $user instanceof User ? $user->email : null;
                $actorName = $user instanceof User ? $user->name : null;

                $auditLogger->log(
                    tenant: $tenant,
                    action: 'provider_connection.connection_type_changed',
                    context: [
                        'metadata' => static::targetScopeAuditMetadata($record, [
                            'from_connection_type' => ProviderConnectionType::Platform->value,
                            'to_connection_type' => ProviderConnectionType::Dedicated->value,
                            'client_id' => (string) $data['client_id'],
                            'source' => $source,
                        ]),
                    ],
                    actorId: $actorId,
                    actorEmail: $actorEmail,
                    actorName: $actorName,
                    resourceType: 'provider_connection',
                    resourceId: (string) $record->getKey(),
                    status: 'success',
                );

                Notification::make()
                    ->title('Dedicated override enabled')
                    ->success()
                    ->send();
            });

        if (is_string($modalDescription) && $modalDescription !== '') {
            $action->modalDescription($modalDescription);
        }

        return UiEnforcement::forAction($action)
            ->requireCapability(Capabilities::PROVIDER_MANAGE_DEDICATED)
            ->preserveVisibility()
            ->apply();
    }

    public static function makeRotateDedicatedCredentialAction(?string $modalDescription = null): Actions\Action
    {
        $action = Actions\Action::make('rotate_dedicated_credential')
            ->label('Rotate dedicated credential')
            ->icon('heroicon-o-arrow-path')
            ->color('primary')
            ->requiresConfirmation()
            ->visible(fn (ProviderConnection $record): bool => $record->connection_type === ProviderConnectionType::Dedicated)
            ->form([
                TextInput::make('client_id')
                    ->label('Dedicated app (client) ID')
                    ->default(function (ProviderConnection $record): string {
                        $payload = $record->credential?->payload;

                        return is_array($payload) ? (string) ($payload['client_id'] ?? '') : '';
                    })
                    ->required()
                    ->maxLength(255),
                TextInput::make('client_secret')
                    ->label('Dedicated client secret')
                    ->password()
                    ->required()
                    ->maxLength(255),
            ])
            ->action(function (array $data, ProviderConnection $record, ProviderConnectionMutationService $mutations): void {
                $tenant = static::resolveTenantForRecord($record);

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

                $mutations->enableDedicatedOverride(
                    connection: $record,
                    clientId: (string) $data['client_id'],
                    clientSecret: (string) $data['client_secret'],
                );

                Notification::make()
                    ->title('Dedicated credential rotated')
                    ->success()
                    ->send();
            });

        if (is_string($modalDescription) && $modalDescription !== '') {
            $action->modalDescription($modalDescription);
        }

        return UiEnforcement::forAction($action)
            ->requireCapability(Capabilities::PROVIDER_MANAGE_DEDICATED)
            ->preserveVisibility()
            ->apply();
    }

    public static function makeDeleteDedicatedCredentialAction(?string $modalDescription = null): Actions\Action
    {
        $action = Actions\Action::make('delete_dedicated_credential')
            ->label('Delete dedicated credential')
            ->icon('heroicon-o-trash')
            ->color('danger')
            ->requiresConfirmation()
            ->visible(fn (ProviderConnection $record): bool => $record->connection_type === ProviderConnectionType::Dedicated
                && $record->credential()->exists())
            ->action(function (ProviderConnection $record, ProviderConnectionMutationService $mutations): void {
                $tenant = static::resolveTenantForRecord($record);

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

                $mutations->deleteDedicatedCredential($record);

                Notification::make()
                    ->title('Dedicated credential deleted')
                    ->warning()
                    ->send();
            });

        if (is_string($modalDescription) && $modalDescription !== '') {
            $action->modalDescription($modalDescription);
        }

        return UiEnforcement::forAction($action)
            ->requireCapability(Capabilities::PROVIDER_MANAGE_DEDICATED)
            ->preserveVisibility()
            ->apply();
    }

    public static function makeRevertToPlatformAction(string $source, ?string $modalDescription = null): Actions\Action
    {
        $action = Actions\Action::make('revert_to_platform')
            ->label('Revert to platform')
            ->icon('heroicon-o-arrow-uturn-left')
            ->color('gray')
            ->requiresConfirmation()
            ->visible(fn (ProviderConnection $record): bool => $record->connection_type === ProviderConnectionType::Dedicated)
            ->action(function (ProviderConnection $record, ProviderConnectionMutationService $mutations, AuditLogger $auditLogger) use ($source): void {
                $tenant = static::resolveTenantForRecord($record);

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

                $mutations->revertToPlatform($record);

                $user = auth()->user();
                $actorId = $user instanceof User ? (int) $user->getKey() : null;
                $actorEmail = $user instanceof User ? $user->email : null;
                $actorName = $user instanceof User ? $user->name : null;

                $auditLogger->log(
                    tenant: $tenant,
                    action: 'provider_connection.connection_type_changed',
                    context: [
                        'metadata' => static::targetScopeAuditMetadata($record, [
                            'from_connection_type' => ProviderConnectionType::Dedicated->value,
                            'to_connection_type' => ProviderConnectionType::Platform->value,
                            'source' => $source,
                        ]),
                    ],
                    actorId: $actorId,
                    actorEmail: $actorEmail,
                    actorName: $actorName,
                    resourceType: 'provider_connection',
                    resourceId: (string) $record->getKey(),
                    status: 'success',
                );

                Notification::make()
                    ->title('Connection reverted to platform')
                    ->success()
                    ->send();
            });

        if (is_string($modalDescription) && $modalDescription !== '') {
            $action->modalDescription($modalDescription);
        }

        return UiEnforcement::forAction($action)
            ->requireCapability(Capabilities::PROVIDER_MANAGE_DEDICATED)
            ->preserveVisibility()
            ->apply();
    }

    public static function makeEnableConnectionAction(): Actions\Action
    {
        return UiEnforcement::forAction(
            Actions\Action::make('enable_connection')
                ->label('Enable connection')
                ->icon('heroicon-o-play')
                ->color('success')
                ->requiresConfirmation()
                ->visible(fn (ProviderConnection $record): bool => ! (bool) $record->is_enabled)
                ->action(function (ProviderConnection $record, AuditLogger $auditLogger): void {
                    $tenant = static::resolveTenantForRecord($record);

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

                    $hadCredentials = $record->credential()->exists();
                    $previousLifecycle = (bool) $record->is_enabled;
                    $verificationStatus = $hadCredentials ? ProviderVerificationStatus::Unknown : ProviderVerificationStatus::Blocked;
                    $errorReasonCode = $hadCredentials ? null : ProviderReasonCodes::ProviderCredentialMissing;
                    $errorMessage = $hadCredentials ? null : 'Provider connection credentials are missing.';

                    $record->update([
                        'is_enabled' => true,
                        'verification_status' => $verificationStatus->value,
                        'last_health_check_at' => null,
                        'last_error_reason_code' => $errorReasonCode,
                        'last_error_message' => $errorMessage,
                    ]);

                    $user = auth()->user();
                    $actorId = $user instanceof User ? (int) $user->getKey() : null;
                    $actorEmail = $user instanceof User ? $user->email : null;
                    $actorName = $user instanceof User ? $user->name : null;

                    $auditLogger->log(
                        tenant: $tenant,
                        action: 'provider_connection.enabled',
                        context: [
                            'metadata' => static::targetScopeAuditMetadata($record, [
                                'from_lifecycle' => $previousLifecycle ? 'enabled' : 'disabled',
                                'to_lifecycle' => 'enabled',
                                'verification_status' => $verificationStatus->value,
                                'credentials_present' => $hadCredentials,
                            ]),
                        ],
                        actorId: $actorId,
                        actorEmail: $actorEmail,
                        actorName: $actorName,
                        resourceType: 'provider_connection',
                        resourceId: (string) $record->getKey(),
                        status: 'success',
                    );

                    if (! $hadCredentials) {
                        Notification::make()
                            ->title('Connection enabled (credentials missing)')
                            ->body('Add credentials before running checks or operations.')
                            ->warning()
                            ->send();

                        return;
                    }

                    Notification::make()
                        ->title('Provider connection enabled')
                        ->success()
                        ->send();
                })
        )
            ->preserveVisibility()
            ->requireCapability(Capabilities::PROVIDER_MANAGE)
            ->apply();
    }

    public static function makeDisableConnectionAction(): Actions\Action
    {
        return UiEnforcement::forAction(
            Actions\Action::make('disable_connection')
                ->label('Disable connection')
                ->icon('heroicon-o-archive-box-x-mark')
                ->color('danger')
                ->requiresConfirmation()
                ->visible(fn (ProviderConnection $record): bool => (bool) $record->is_enabled)
                ->action(function (ProviderConnection $record, AuditLogger $auditLogger): void {
                    $tenant = static::resolveTenantForRecord($record);

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

                    $previousLifecycle = (bool) $record->is_enabled;

                    $record->update([
                        'is_enabled' => false,
                    ]);

                    $user = auth()->user();
                    $actorId = $user instanceof User ? (int) $user->getKey() : null;
                    $actorEmail = $user instanceof User ? $user->email : null;
                    $actorName = $user instanceof User ? $user->name : null;

                    $auditLogger->log(
                        tenant: $tenant,
                        action: 'provider_connection.disabled',
                        context: [
                            'metadata' => static::targetScopeAuditMetadata($record, [
                                'from_lifecycle' => $previousLifecycle ? 'enabled' : 'disabled',
                                'to_lifecycle' => 'disabled',
                            ]),
                        ],
                        actorId: $actorId,
                        actorEmail: $actorEmail,
                        actorName: $actorName,
                        resourceType: 'provider_connection',
                        resourceId: (string) $record->getKey(),
                        status: 'success',
                    );

                    Notification::make()
                        ->title('Provider connection disabled')
                        ->warning()
                        ->send();
                })
        )
            ->preserveVisibility()
            ->requireCapability(Capabilities::PROVIDER_MANAGE)
            ->apply();
    }

    private static function recordAllowsProviderExecution(ProviderConnection $record): bool
    {
        $tenant = static::resolveTenantForRecord($record);
        $user = auth()->user();

        return $tenant instanceof ManagedEnvironment
            && $user instanceof User
            && $user->canAccessTenant($tenant)
            && (bool) $record->is_enabled;
    }

    private static function handleCheckConnectionAction(ProviderConnection $record, StartVerification $verification, mixed $livewire = null): void
    {
        $tenant = static::resolveTenantForRecord($record);
        $user = auth()->user();

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

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

        $result = $verification->providerConnectionCheck(
            tenant: $tenant,
            connection: $record,
            initiator: $user,
        );

        $runUrl = OperationRunLinks::view($result->run, $tenant);
        $extraActions = $result->status === 'started'
            ? []
            : [
                Actions\Action::make('manage_connections')
                    ->label('Manage Provider Connections')
                    ->url(static::getUrl('index', tenant: $tenant)),
            ];
        $notification = app(ProviderOperationStartResultPresenter::class)->notification(
            result: $result,
            blockedTitle: 'Connection check blocked',
            runUrl: $runUrl,
            extraActions: $extraActions,
        );

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

            return;
        }

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

            $notification->send();

            return;
        }

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

            return;
        }

        OpsUxBrowserEvents::dispatchRunEnqueued($livewire);

        $notification->send();
    }

    /**
     * @param  callable(ManagedEnvironment, User, ProviderConnection, OperationRun): void  $dispatcher
     */
    private static function handleProviderOperationAction(
        ProviderConnection $record,
        ProviderOperationStartGate $gate,
        string $operationType,
        string $blockedTitle,
        callable $dispatcher,
        mixed $livewire = null,
    ): void {
        $tenant = static::resolveTenantForRecord($record);
        $user = auth()->user();

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

        $result = $gate->start(
            tenant: $tenant,
            connection: $record,
            operationType: $operationType,
            dispatcher: function (OperationRun $operationRun) use ($dispatcher, $record, $tenant, $user): void {
                $dispatcher($tenant, $user, $record, $operationRun);
            },
            initiator: $user,
        );

        $notification = app(ProviderOperationStartResultPresenter::class)->notification(
            result: $result,
            blockedTitle: $blockedTitle,
            runUrl: OperationRunLinks::view($result->run, $tenant),
        );

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

            return;
        }

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

            $notification->send();

            return;
        }

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

            return;
        }

        OpsUxBrowserEvents::dispatchRunEnqueued($livewire);

        $notification->send();
    }

    public static function getEloquentQuery(): Builder
    {
        $query = parent::getEloquentQuery()
            ->with('tenant');

        return static::applyMembershipScope($query)
            ->latest('provider_connections.id');
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListProviderConnections::route('/'),
            'create' => Pages\CreateProviderConnection::route('/create'),
            'view' => Pages\ViewProviderConnection::route('/{record}'),
            'edit' => Pages\EditProviderConnection::route('/{record}/edit'),
        ];
    }

    private static function normalizeTenantExternalId(mixed $tenant): ?string
    {
        if ($tenant instanceof ManagedEnvironment) {
            return (string) $tenant->slug;
        }

        if (is_string($tenant) && $tenant !== '') {
            return $tenant;
        }

        if (is_numeric($tenant)) {
            $tenantModel = ManagedEnvironment::query()->whereKey((int) $tenant)->first();

            if ($tenantModel instanceof ManagedEnvironment) {
                return (string) $tenantModel->slug;
            }
        }

        return null;
    }

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

        if ($tenantExternalId === null && $tenant instanceof ManagedEnvironment) {
            $tenantExternalId = (string) $tenant->slug;
        }

        if ($tenantExternalId === null) {
            $record = $parameters['record'] ?? null;

            if ($record instanceof ProviderConnection) {
                $tenantExternalId = static::resolveTenantForRecord($record)?->slug;
            }
        }

        if ($tenantExternalId === null && ! $isIndexUrl) {
            $tenantExternalId = static::resolveScopedTenant()?->slug;
        }

        if (! array_key_exists('environment_id', $parameters) && is_string($tenantExternalId) && $tenantExternalId !== '') {
            $environment = static::resolveTenantByExternalId($tenantExternalId);

            if ($environment instanceof ManagedEnvironment) {
                $parameters['environment_id'] = (int) $environment->getKey();
            }
        }

        return parent::getUrl($name, $parameters, $isAbsolute, $panel, null, $shouldGuessMissingParameters);
    }
}
