<?php

namespace App\Filament\Resources\EntraGroupResource\Pages;

use App\Filament\Resources\EntraGroupResource;
use App\Jobs\EntraGroupSyncJob;
use App\Models\Tenant;
use App\Models\User;
use App\Services\Directory\EntraGroupSelection;
use App\Services\OperationRunService;
use App\Support\Auth\Capabilities;
use App\Support\OperationRunLinks;
use App\Support\OpsUx\OperationUxPresenter;
use App\Support\OpsUx\OpsUxBrowserEvents;
use App\Support\Rbac\UiEnforcement;
use Filament\Actions\Action;
use Filament\Resources\Pages\ListRecords;

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

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

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

                        $selectionKey = EntraGroupSelection::allGroupsV1();

                        // --- Phase 3: Canonical Operation Run Start ---
                        /** @var OperationRunService $opService */
                        $opService = app(OperationRunService::class);
                        $opRun = $opService->ensureRunWithIdentity(
                            tenant: $tenant,
                            type: 'entra_group_sync',
                            identityInputs: ['selection_key' => $selectionKey],
                            context: [
                                'selection_key' => $selectionKey,
                                'trigger' => 'manual',
                            ],
                            initiator: $user,
                        );

                        if (! $opRun->wasRecentlyCreated && in_array($opRun->status, ['queued', 'running'])) {
                            OpsUxBrowserEvents::dispatchRunEnqueued($this);
                            OperationUxPresenter::alreadyQueuedToast((string) $opRun->type)
                                ->actions([
                                    Action::make('view_run')
                                        ->label('View Run')
                                        ->url(OperationRunLinks::view($opRun, $tenant)),
                                ])
                                ->send();

                            return;
                        }
                        // ----------------------------------------------

                        dispatch(new EntraGroupSyncJob(
                            tenantId: (int) $tenant->getKey(),
                            selectionKey: $selectionKey,
                            slotKey: null,
                            runId: null,
                            operationRun: $opRun
                        ));

                        OpsUxBrowserEvents::dispatchRunEnqueued($this);
                        OperationUxPresenter::queuedToast((string) $opRun->type)
                            ->actions([
                                Action::make('view_run')
                                    ->label('View Run')
                                    ->url(OperationRunLinks::view($opRun, $tenant)),
                            ])
                            ->send();
                    })
            )
                ->requireCapability(Capabilities::TENANT_SYNC)
                ->tooltip('You do not have permission to sync groups.')
                ->apply(),
        ];
    }
}
