<?php

namespace App\Concerns;

use App\Models\Workspace;
use Illuminate\Database\Eloquent\Model;

trait HasWorkspaceScope
{
    /**
     * Resolve the current workspace from the session.
     */
    protected function currentWorkspace(): Workspace
    {
        return auth()->user()->workspaces()
            ->where('workspaces.id', session('current_workspace_id'))
            ->firstOrFail();
    }

    /**
     * Verify the given resource belongs to the current workspace.
     * Aborts with 404 if the resource does not belong to the workspace.
     */
    protected function authorizeWorkspaceAccess(Model $resource): void
    {
        if ($resource->workspace_id !== (int) session('current_workspace_id')) {
            abort(404);
        }
    }
}
