<?php

declare(strict_types=1);

namespace App\Filament\System\Pages\Directory;

use App\Models\OperationRun;
use App\Models\PlatformUser;
use App\Models\Tenant;
use App\Models\Workspace;
use App\Support\Auth\PlatformCapabilities;
use App\Support\OperationCatalog;
use App\Support\System\SystemDirectoryLinks;
use App\Support\System\SystemOperationRunLinks;
use Filament\Pages\Page;
use Illuminate\Support\Collection;

class ViewWorkspace extends Page
{
    protected static bool $shouldRegisterNavigation = false;

    protected static ?string $slug = 'directory/workspaces/{workspace}';

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

    public Workspace $workspace;

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

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

    public function mount(Workspace $workspace): void
    {
        $workspace->loadCount('tenants');

        $this->workspace = $workspace;
    }

    /**
     * @return Collection<int, Tenant>
     */
    public function workspaceTenants(): Collection
    {
        return Tenant::query()
            ->where('workspace_id', (int) $this->workspace->getKey())
            ->orderBy('name')
            ->limit(10)
            ->get(['id', 'name', 'status', 'workspace_id']);
    }

    /**
     * @return Collection<int, array{id: int, label: string, started: string, url: string}>
     */
    public function recentRuns(): Collection
    {
        return OperationRun::query()
            ->where('workspace_id', (int) $this->workspace->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 adminWorkspaceUrl(): string
    {
        return SystemDirectoryLinks::adminWorkspace($this->workspace);
    }

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