<?php

declare(strict_types=1);

namespace App\Filament\Pages;

use App\Filament\Concerns\ResolvesPanelTenantContext;
use App\Models\User;
use App\Services\Auth\ManagedEnvironmentDiagnosticsService;
use App\Services\Auth\ManagedEnvironmentMembershipManager;
use App\Support\Auth\Capabilities;
use App\Support\Rbac\UiEnforcement;
use App\Support\Rbac\UiTooltips;
use App\Support\Ui\ActionSurface\ActionSurfaceDeclaration;
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceProfile;
use App\Support\Ui\ActionSurface\Enums\ActionSurfaceSlot;
use Filament\Actions\Action;
use Filament\Pages\Page;

class EnvironmentDiagnostics extends Page
{
    use ResolvesPanelTenantContext;

    protected static bool $shouldRegisterNavigation = false;

    protected static ?string $slug = 'diagnostics';

    protected string $view = 'filament.pages.environment-diagnostics';

    public static function actionSurfaceDeclaration(): ActionSurfaceDeclaration
    {
        return ActionSurfaceDeclaration::forPage(ActionSurfaceProfile::ListOnlyReadOnly)
            ->satisfy(ActionSurfaceSlot::ListHeader, 'Header exposes capability-gated tenant repair actions when inconsistent membership state is detected.')
            ->exempt(ActionSurfaceSlot::InspectAffordance, 'ManagedEnvironment diagnostics is already the singleton diagnostic surface for the active tenant.')
            ->exempt(ActionSurfaceSlot::ListRowMoreMenu, 'The diagnostics page does not render row-level secondary actions.')
            ->exempt(ActionSurfaceSlot::ListBulkMoreGroup, 'The diagnostics page does not expose bulk actions.')
            ->exempt(ActionSurfaceSlot::ListEmptyState, 'Diagnostics content is always rendered instead of a list-style empty state.');
    }

    public bool $missingOwner = false;

    public bool $hasDuplicateMembershipsForCurrentUser = false;

    public function mount(): void
    {
        $tenant = static::resolveTenantContextForCurrentPanelOrFail();
        $this->missingOwner = app(ManagedEnvironmentDiagnosticsService::class)->tenantHasNoOwners($tenant);

        $user = auth()->user();
        if (! $user instanceof User) {
            abort(403, 'Not allowed');
        }

        $this->hasDuplicateMembershipsForCurrentUser = app(ManagedEnvironmentDiagnosticsService::class)
            ->userHasDuplicateMemberships($tenant, $user);
    }

    /**
     * @return array<Action>
     */
    protected function getHeaderActions(): array
    {
        return [
            UiEnforcement::forAction(
                Action::make('bootstrapOwner')
                    ->label('Bootstrap owner')
                    ->requiresConfirmation()
                    ->action(fn () => $this->bootstrapOwner()),
            )
                ->requireCapability(Capabilities::TENANT_MANAGE)
                ->destructive()
                ->tooltip(UiTooltips::INSUFFICIENT_PERMISSION)
                ->apply()
                ->visible(fn (): bool => $this->missingOwner),

            UiEnforcement::forAction(
                Action::make('mergeDuplicateMemberships')
                    ->label('Merge duplicate access scopes')
                    ->requiresConfirmation()
                    ->action(fn () => $this->mergeDuplicateMemberships()),
            )
                ->requireCapability(Capabilities::TENANT_MANAGE)
                ->destructive()
                ->tooltip(UiTooltips::INSUFFICIENT_PERMISSION)
                ->apply()
                ->visible(fn (): bool => $this->hasDuplicateMembershipsForCurrentUser),
        ];
    }

    public function bootstrapOwner(): void
    {
        $tenant = static::resolveTenantContextForCurrentPanelOrFail();

        $user = auth()->user();
        if (! $user instanceof User) {
            abort(403, 'Not allowed');
        }

        app(ManagedEnvironmentMembershipManager::class)->grantScope($tenant, $user, $user, sourceRef: 'diagnostic');

        $this->mount();
    }

    public function mergeDuplicateMemberships(): void
    {
        $tenant = static::resolveTenantContextForCurrentPanelOrFail();

        $user = auth()->user();
        if (! $user instanceof User) {
            abort(403, 'Not allowed');
        }

        app(ManagedEnvironmentDiagnosticsService::class)->mergeDuplicateMembershipsForUser($tenant, $user, $user);

        $this->mount();
    }
}
