<?php

use App\Concerns\HasWorkspaceScope;
use App\Models\Client;
use App\Models\User;
use App\Models\Workspace;

function createScopeChecker(): object
{
    return new class
    {
        use HasWorkspaceScope;

        public function getWorkspace(): \App\Models\Workspace
        {
            return $this->currentWorkspace();
        }

        public function checkAccess(\Illuminate\Database\Eloquent\Model $resource): void
        {
            $this->authorizeWorkspaceAccess($resource);
        }
    };
}

test('currentWorkspace resolves workspace from session', function () {
    $user = User::factory()->create();
    $workspace = Workspace::factory()->create();
    $workspace->users()->attach($user->id, ['role' => 'owner']);
    session(['current_workspace_id' => $workspace->id]);
    $this->actingAs($user);

    $checker = createScopeChecker();
    $resolved = $checker->getWorkspace();

    expect($resolved->id)->toBe($workspace->id);
});

test('currentWorkspace fails when user not in workspace', function () {
    $user = User::factory()->create();
    $workspace = Workspace::factory()->create();
    session(['current_workspace_id' => $workspace->id]);
    $this->actingAs($user);

    $checker = createScopeChecker();
    $checker->getWorkspace();
})->throws(Illuminate\Database\Eloquent\ModelNotFoundException::class);

test('authorizeWorkspaceAccess passes for matching workspace', function () {
    $workspace = Workspace::factory()->create();
    $client = Client::factory()->create(['workspace_id' => $workspace->id]);
    session(['current_workspace_id' => $workspace->id]);

    $checker = createScopeChecker();
    $checker->checkAccess($client);

    expect(true)->toBeTrue(); // No exception thrown
});

test('authorizeWorkspaceAccess aborts 404 for mismatched workspace', function () {
    $workspace1 = Workspace::factory()->create();
    $workspace2 = Workspace::factory()->create();
    $client = Client::factory()->create(['workspace_id' => $workspace1->id]);
    session(['current_workspace_id' => $workspace2->id]);

    $checker = createScopeChecker();
    $checker->checkAccess($client);
})->throws(Symfony\Component\HttpKernel\Exception\NotFoundHttpException::class);
