<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Support\Tenants\TenantPageCategory;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

final class ClearTenantContextController
{
    public function __invoke(Request $request): RedirectResponse
    {
        Filament::setTenant(null, true);

        $workspaceContext = app(WorkspaceContext::class);

        $workspaceContext->clearRememberedTenantContext($request);

        $previousUrl = url()->previous();

        $previousHost = parse_url((string) $previousUrl, PHP_URL_HOST);
        $previousPath = (string) (parse_url((string) $previousUrl, PHP_URL_PATH) ?? '');

        if ($previousHost !== null && $previousHost !== $request->getHost()) {
            return redirect()->route('admin.operations.index');
        }

        if ($this->isTenantScopedEvidencePath($previousPath)) {
            return redirect()->route('admin.evidence.overview');
        }

        if (TenantPageCategory::fromPath($previousPath) === TenantPageCategory::TenantBound) {
            $workspace = $workspaceContext->currentWorkspace($request);

            if ($workspace !== null) {
                return redirect()->route('admin.workspace.managed-tenants.index', ['workspace' => $workspace]);
            }

            return redirect()->route('admin.home');
        }

        if ($previousPath === '' || $previousPath === '/admin/clear-tenant-context') {
            return redirect()->route('admin.operations.index');
        }

        return redirect()->to((string) $previousUrl);
    }

    private function isTenantScopedEvidencePath(string $previousPath): bool
    {
        if ($previousPath === '/admin/evidence') {
            return true;
        }

        if (! str_starts_with($previousPath, '/admin/evidence/')) {
            return false;
        }

        return ! str_starts_with($previousPath, '/admin/evidence/overview');
    }
}
