<?php

namespace App\Filament\Resources\ProviderConnectionResource\Pages;

use App\Filament\Resources\ProviderConnectionResource;
use App\Models\ProviderConnection;
use App\Models\ManagedEnvironment;
use App\Support\Auth\Capabilities;
use App\Support\Links\RequiredPermissionsLinks;
use App\Support\Rbac\UiEnforcement;
use Filament\Actions;
use Filament\Resources\Pages\ViewRecord;

class ViewProviderConnection extends ViewRecord
{
    protected static string $resource = ProviderConnectionResource::class;

    protected function getHeaderActions(): array
    {
        $tenant = $this->currentTenant();

        return [
            UiEnforcement::forAction(
                Actions\Action::make('grant_admin_consent')
                    ->label('Grant admin consent')
                    ->icon('heroicon-o-clipboard-document')
                    ->url(function () use ($tenant): ?string {
                        return $tenant instanceof ManagedEnvironment
                            ? RequiredPermissionsLinks::adminConsentPrimaryUrl($tenant)
                            : null;
                    })
                    ->visible(fn (): bool => $tenant instanceof ManagedEnvironment)
                    ->openUrlInNewTab()
            )
                ->requireCapability(Capabilities::PROVIDER_MANAGE)
                ->apply(),
            Actions\ActionGroup::make($this->sharedConnectionActions())
                ->label('More')
                ->icon('heroicon-o-ellipsis-vertical')
                ->color('gray'),
        ];
    }

    /**
     * @return array<int, Actions\Action>
     */
    private function sharedConnectionActions(): array
    {
        return [
            ProviderConnectionResource::makeEditNavigationAction(),
            ProviderConnectionResource::makeCheckConnectionAction(),
            ProviderConnectionResource::makeInventorySyncAction(),
            ProviderConnectionResource::makeComplianceSnapshotAction(),
            ProviderConnectionResource::makeSetDefaultAction(),
            ProviderConnectionResource::makeEnableDedicatedOverrideAction(
                source: 'provider_connection.view_page',
                modalDescription: 'Dedicated credentials are stored encrypted and reset consent to the dedicated app registration.',
            ),
            ProviderConnectionResource::makeRotateDedicatedCredentialAction(),
            ProviderConnectionResource::makeDeleteDedicatedCredentialAction(),
            ProviderConnectionResource::makeRevertToPlatformAction(source: 'provider_connection.view_page'),
            ProviderConnectionResource::makeEnableConnectionAction(),
            ProviderConnectionResource::makeDisableConnectionAction(),
        ];
    }

    private function currentTenant(): ?ManagedEnvironment
    {
        if (! $this->record instanceof ProviderConnection) {
            return null;
        }

        return ProviderConnectionResource::resolveTenantForRecord($this->record);
    }
}
