<?php

use App\Domains\Workspace\Models\Workspace;
use App\Domains\Workspace\Services\CurrentWorkspace;

if (! function_exists('current_workspace')) {
    function current_workspace(): ?Workspace
    {
        $ws = app(CurrentWorkspace::class)->get();
        if ($ws) {
            return $ws;
        }

        // Backward-compat fallback: tests and legacy code may bind via app()->instance()
        if (app()->bound('current_workspace')) {
            /** @var Workspace $ws */
            $ws = app('current_workspace');
            app(CurrentWorkspace::class)->set($ws);

            return $ws;
        }

        return null;
    }
}

if (! function_exists('require_workspace')) {
    function require_workspace(): Workspace
    {
        $ws = current_workspace();
        if (! $ws) {
            throw new RuntimeException('No current workspace set. Route missing workspace.resolve middleware?');
        }

        return $ws;
    }
}
