<?php

declare(strict_types=1);

use App\Models\OperationRun;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceMembership;
use App\Support\Workspaces\WorkspaceContext;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('returns 404 when a non-member tries to view another workspace operation run', function (): void {
    $workspaceA = Workspace::factory()->create();
    $workspaceB = Workspace::factory()->create();

    $user = User::factory()->create();

    WorkspaceMembership::factory()->create([
        'workspace_id' => $workspaceA->getKey(),
        'user_id' => $user->getKey(),
        'role' => 'owner',
    ]);

    $tenantB = ManagedEnvironment::factory()->create([
        'status' => 'active',
        'workspace_id' => (int) $workspaceB->getKey(),
    ]);

    $runB = OperationRun::factory()->create([
        'managed_environment_id' => (int) $tenantB->getKey(),
        'workspace_id' => (int) $workspaceB->getKey(),
        'type' => 'policy.sync',
        'initiator_name' => 'WorkspaceB',
    ]);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $workspaceA->getKey()])
        ->get(route('admin.operations.view', [
            'workspace' => (int) $workspaceB->getKey(),
            'run' => (int) $runB->getKey(),
        ]))
        ->assertNotFound();
});

it('returns 403 when a workspace member without workspace.manage tries to edit a workspace', function (): void {
    $user = User::factory()->create();

    $workspace = Workspace::factory()->create();
    WorkspaceMembership::factory()->create([
        'workspace_id' => $workspace->getKey(),
        'user_id' => $user->getKey(),
        'role' => 'manager',
    ]);

    $this->actingAs($user)
        ->withSession([WorkspaceContext::SESSION_KEY => (int) $workspace->getKey()])
        ->get('/admin/workspaces/'.(int) $workspace->getKey().'/edit')
        ->assertForbidden();
});
