<?php

namespace App\Filament\Resources\EntraGroupResource\Pages;

use App\Filament\Resources\EntraGroupResource;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Services\Directory\EntraGroupSyncService;
use App\Support\Auth\Capabilities;
use App\Support\Filament\CanonicalAdminEnvironmentFilterState;
use App\Support\OperationRunLinks;
use App\Support\OpsUx\OpsUxBrowserEvents;
use App\Support\OpsUx\ProviderOperationStartResultPresenter;
use App\Support\Rbac\UiEnforcement;
use Filament\Actions\Action;
use Filament\Facades\Filament;
use Filament\Resources\Pages\ListRecords;

class ListEntraGroups extends ListRecords
{
    protected static string $resource = EntraGroupResource::class;

    public function mount(): void
    {
        app(CanonicalAdminEnvironmentFilterState::class)->sync(
            $this->getTableFiltersSessionKey(),
            request: request(),
            environmentFilterName: null,
        );

        if (
            Filament::getCurrentPanel()?->getId() === 'admin'
            && ! EntraGroupResource::panelTenantContext() instanceof ManagedEnvironment
        ) {
            abort(404);
        }

        parent::mount();
    }

    protected function getHeaderActions(): array
    {
        $tenant = EntraGroupResource::panelTenantContext();

        return [
            Action::make('view_operations')
                ->label('Operations')
                ->icon('heroicon-o-clock')
                ->url(fn (): string => OperationRunLinks::index($tenant))
                ->visible(fn (): bool => $tenant instanceof ManagedEnvironment),
            UiEnforcement::forAction(
                Action::make('sync_groups')
                    ->label('Sync Groups')
                    ->icon('heroicon-o-arrow-path')
                    ->color('primary')
                    ->action(function (EntraGroupSyncService $syncService): void {
                        $user = auth()->user();
                        $tenant = EntraGroupResource::panelTenantContext();

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

                        $result = $syncService->startManualSync($tenant, $user);
                        $notification = app(ProviderOperationStartResultPresenter::class)->notification(
                            result: $result,
                            blockedTitle: 'Directory groups sync blocked',
                            runUrl: OperationRunLinks::view($result->run, $tenant),
                        );

                        if (in_array($result->status, ['started', 'deduped', 'scope_busy'], true)) {
                            OpsUxBrowserEvents::dispatchRunEnqueued($this);
                        }

                        $notification->send();
                    })
            )
                ->requireCapability(Capabilities::TENANT_SYNC)
                ->tooltip('You do not have permission to sync groups.')
                ->apply(),
        ];
    }
}
