<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Support\Navigation\AdminSurfaceScope;
use App\Support\OperationRunLinks;
use App\Support\Workspaces\WorkspaceContext;
use Filament\Facades\Filament;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

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

        $workspaceContext = app(WorkspaceContext::class);

        $workspaceContext->clearRememberedEnvironmentContext($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()->to(OperationRunLinks::index());
        }

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

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

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

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

        if ($previousPath === '' || $previousPath === '/admin/clear-environment-context') {
            return redirect()->to(OperationRunLinks::index());
        }

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

    private function isEnvironmentScopedEvidencePath(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');
    }
}
