<?php

use App\Models\TenantMembership;
use App\Services\Auth\TenantMembershipManager;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('prevents demoting the last remaining owner', function () {
    [$actor, $tenant] = createUserWithTenant(role: 'owner');

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

    $manager = app(TenantMembershipManager::class);

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

    expect($callback)->toThrow(DomainException::class, 'You cannot demote the last remaining owner.');
});

it('prevents removing the last remaining owner', function () {
    [$actor, $tenant] = createUserWithTenant(role: 'owner');

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

    $manager = app(TenantMembershipManager::class);

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

    expect($callback)->toThrow(DomainException::class, 'You cannot remove the last remaining owner.');
});
