<?php

use App\Models\User;
use App\Models\WorkspaceMembership;
use App\Services\Auth\ManagedEnvironmentMembershipManager;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('can add and remove explicit environment access scopes without changing roles', function () {
    [$actor, $tenant] = createUserWithTenant(role: 'owner');
    $member = User::factory()->create();
    WorkspaceMembership::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'user_id' => (int) $member->getKey(),
        'role' => 'readonly',
    ]);

    $manager = app(ManagedEnvironmentMembershipManager::class);

    $membership = $manager->addMember($tenant, $actor, $member, 'readonly');

    $this->assertDatabaseHas('managed_environment_memberships', [
        'id' => $membership->getKey(),
        'managed_environment_id' => $tenant->getKey(),
        'user_id' => $member->getKey(),
        'role' => 'readonly',
        'source' => 'manual',
    ]);

    expect(fn () => $manager->changeRole($tenant, $actor, $membership, 'operator'))
        ->toThrow(DomainException::class);

    $manager->removeMember($tenant, $actor, $membership);

    $this->assertDatabaseMissing('managed_environment_memberships', [
        'managed_environment_id' => $tenant->getKey(),
        'user_id' => $member->getKey(),
    ]);
});
