<?php

declare(strict_types=1);

namespace App\Filament\System\Pages\Directory;

use App\Filament\System\Pages\Directory\Concerns\BuildsCustomerHealthDecisionData;
use App\Models\OperationRun;
use App\Models\PlatformUser;
use App\Models\ProviderConnection;
use App\Models\ManagedEnvironment;
use App\Models\ManagedEnvironmentPermission;
use App\Support\Auth\PlatformCapabilities;
use App\Support\CustomerHealth\WorkspaceHealthSummaryQuery;
use App\Support\OperationCatalog;
use App\Support\System\SystemDirectoryLinks;
use App\Support\System\SystemOperationRunLinks;
use App\Support\SystemConsole\SystemConsoleWindow;
use Filament\Pages\Page;
use Illuminate\Support\Collection;

class ViewTenant extends Page
{
    use BuildsCustomerHealthDecisionData;

    protected static bool $shouldRegisterNavigation = false;

    protected static ?string $slug = 'directory/tenants/{tenant}';

    protected string $view = 'filament.system.pages.directory.view-tenant';

    public ManagedEnvironment $tenant;

    public static function canAccess(): bool
    {
        $user = auth('platform')->user();

        return $user instanceof PlatformUser
            && $user->hasCapability(PlatformCapabilities::DIRECTORY_VIEW);
    }

    public function mount(ManagedEnvironment $tenant): void
    {
        $tenant->load('workspace');

        $this->tenant = $tenant;
    }

    /**
     * @return Collection<int, ProviderConnection>
     */
    public function providerConnections(): Collection
    {
        return ProviderConnection::query()
            ->where('managed_environment_id', (int) $this->tenant->getKey())
            ->orderByDesc('is_default')
            ->orderBy('provider')
            ->get([
                'id',
                'display_name',
                'provider',
                'is_default',
                'is_enabled',
                'consent_status',
                'verification_status',
                'last_health_check_at',
                'last_error_reason_code',
            ]);
    }

    /**
     * @return Collection<int, ManagedEnvironmentPermission>
     */
    public function managedEnvironmentPermissions(): Collection
    {
        return ManagedEnvironmentPermission::query()
            ->where('managed_environment_id', (int) $this->tenant->getKey())
            ->orderBy('permission_key')
            ->limit(20)
            ->get(['id', 'permission_key', 'status', 'last_checked_at']);
    }

    /**
     * @return Collection<int, array{id: int, label: string, started: string, url: string}>
     */
    public function recentRuns(): Collection
    {
        return OperationRun::query()
            ->where('managed_environment_id', (int) $this->tenant->getKey())
            ->latest('id')
            ->limit(8)
            ->get(['id', 'type', 'created_at'])
            ->map(fn (OperationRun $run): array => [
                'id' => (int) $run->getKey(),
                'label' => OperationCatalog::label((string) $run->type),
                'started' => $run->created_at?->diffForHumans() ?? '—',
                'url' => SystemOperationRunLinks::view($run),
            ]);
    }

    public function adminTenantUrl(): string
    {
        return SystemDirectoryLinks::adminTenant($this->tenant);
    }

    public function runsUrl(): string
    {
        return SystemOperationRunLinks::index();
    }

    /**
     * @return array{
     *     overall: array{label: string, color: string, icon: string|null},
     *     reason: string,
     *     impact: string,
     *     recommended_action: string,
     *     dominant_dimensions: list<array{label: string, color: string, icon: string|null}>,
     *     window_label: string
     * }|null
     */
    public function customerHealthDecision(): ?array
    {
        $window = SystemConsoleWindow::fromNullable(request()->query('window'));
        $summary = app(WorkspaceHealthSummaryQuery::class)->summaryForWorkspace((int) $this->tenant->workspace_id, $window);

        if (! is_array($summary)) {
            return null;
        }

        return $this->buildCustomerHealthDecision($summary, $window, 'tenant');
    }
}
