<?php

declare(strict_types=1);

namespace App\Support\Workspaces;

use App\Filament\Pages\ChooseTenant;
use App\Filament\Pages\ChooseWorkspace;
use App\Filament\Pages\TenantDashboard;
use App\Models\User;
use App\Models\Workspace;

/**
 * Resolves the explicit post-selection destination after a workspace is set.
 *
 * Tenant-count branching stays available for chooser-driven flows:
 *  - 0 tenants  → Managed Tenants index
 *  - 1 tenant   → Tenant Dashboard directly
 *  - >1 tenants → Choose Tenant page
 */
final class WorkspaceRedirectResolver
{
    /**
     * Resolve the redirect URL for the given workspace + user.
     *
     * Returns a fully qualified URL string.
     */
    public function resolve(Workspace $workspace, User $user): string
    {
        $tenantsQuery = $user->tenants()
            ->where('workspace_id', $workspace->getKey())
            ->where('status', 'active');

        $tenantCount = (int) $tenantsQuery->count();

        if ($tenantCount === 0) {
            return route('admin.workspace.managed-tenants.index', [
                'workspace' => $workspace->slug ?? $workspace->getKey(),
            ]);
        }

        if ($tenantCount === 1) {
            $tenant = $tenantsQuery->first();

            if ($tenant !== null) {
                return TenantDashboard::getUrl(panel: 'tenant', tenant: $tenant);
            }
        }

        return ChooseTenant::getUrl();
    }

    /**
     * Resolve the redirect URL using a workspace ID.
     *
     * Falls back to the chooser page if the workspace cannot be resolved.
     */
    public function resolveFromId(int $workspaceId, User $user): string
    {
        $workspace = Workspace::query()->whereKey($workspaceId)->first();

        if (! $workspace instanceof Workspace) {
            return ChooseWorkspace::getUrl();
        }

        return $this->resolve($workspace, $user);
    }
}
