<?php

declare(strict_types=1);

namespace App\Http\Controllers;

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);

        app(WorkspaceContext::class)->clearLastTenantId($request);

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

        $previousHost = parse_url((string) $previousUrl, PHP_URL_HOST);

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

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