<?php

use App\Filament\Pages\BreakGlassRecovery;
use App\Models\AuditLog;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

it('allows platform superadmin to assign an owner via break-glass recovery and audits it', function () {
    $superadmin = User::factory()->create(['is_platform_superadmin' => true]);
    $this->actingAs($superadmin);

    $tenant = Tenant::factory()->create();
    $targetUser = User::factory()->create();

    Livewire::test(BreakGlassRecovery::class)
        ->callAction('bootstrap_recover', data: [
            'tenant_id' => $tenant->getKey(),
            'user_id' => $targetUser->getKey(),
        ]);

    $this->assertDatabaseHas('tenant_memberships', [
        'tenant_id' => $tenant->getKey(),
        'user_id' => $targetUser->getKey(),
        'role' => 'owner',
        'source' => 'break_glass',
    ]);

    $audit = AuditLog::query()
        ->where('tenant_id', $tenant->getKey())
        ->where('action', 'tenant_membership.bootstrap_recover')
        ->latest('id')
        ->first();

    expect($audit)->not->toBeNull();
});
