<?php

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

uses(RefreshDatabase::class);

it('rejects role changes on managed-environment access scopes', function () {
    [$actor, $tenant] = createUserWithTenant(role: 'owner');

    $membership = ManagedEnvironmentMembership::query()
        ->where('managed_environment_id', $tenant->getKey())
        ->where('user_id', $actor->getKey())
        ->firstOrFail();

    $manager = app(ManagedEnvironmentMembershipManager::class);

    $callback = fn () => $manager->changeRole($tenant, $actor, $membership, 'readonly');

    expect($callback)->toThrow(
        DomainException::class,
        'Managed-environment access scopes do not manage roles. Change the workspace role instead.',
    );
});

it('removes an environment access scope without removing workspace owner authority', function () {
    [$actor, $tenant] = createUserWithTenant(role: 'owner');

    $membership = ManagedEnvironmentMembership::query()
        ->where('managed_environment_id', $tenant->getKey())
        ->where('user_id', $actor->getKey())
        ->firstOrFail();

    $manager = app(ManagedEnvironmentMembershipManager::class);

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

    expect(ManagedEnvironmentMembership::query()->whereKey($membership->getKey())->exists())->toBeFalse()
        ->and(WorkspaceMembership::query()
            ->where('workspace_id', (int) $tenant->workspace_id)
            ->where('user_id', (int) $actor->getKey())
            ->where('role', 'owner')
            ->exists())->toBeTrue();
});
