<?php

use App\Models\User;
use App\Services\Auth\TenantMembershipManager;
use App\Support\TenantRole;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('can add, change role, and remove tenant members', function () {
    [$actor, $tenant] = createUserWithTenant(role: 'owner');
    $member = User::factory()->create();

    $manager = app(TenantMembershipManager::class);

    $membership = $manager->addMember($tenant, $actor, $member, TenantRole::Readonly);

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

    $updated = $manager->changeRole($tenant, $actor, $membership, TenantRole::Operator);

    expect($updated->role)->toBe('operator');

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

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