<?php

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

uses(RefreshDatabase::class);

it('writes audit logs for membership add, role change, and remove without sensitive fields', function () {
    [$actor, $tenant] = createUserWithTenant(role: 'owner');
    $member = User::factory()->create();

    $manager = app(TenantMembershipManager::class);

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

    $actions = AuditLog::query()
        ->where('tenant_id', $tenant->getKey())
        ->whereIn('action', [
            'tenant_membership.add',
            'tenant_membership.role_change',
            'tenant_membership.remove',
        ])
        ->pluck('action')
        ->all();

    expect($actions)->toContain('tenant_membership.add');
    expect($actions)->toContain('tenant_membership.role_change');
    expect($actions)->toContain('tenant_membership.remove');

    $metadata = AuditLog::query()
        ->where('tenant_id', $tenant->getKey())
        ->whereIn('action', [
            'tenant_membership.add',
            'tenant_membership.role_change',
            'tenant_membership.remove',
        ])
        ->get()
        ->pluck('metadata')
        ->all();

    foreach ($metadata as $entry) {
        expect($entry)->toBeArray();
        expect(array_key_exists('app_client_secret', $entry))->toBeFalse();
        expect(array_key_exists('client_secret', $entry))->toBeFalse();
        expect(array_key_exists('refresh_token', $entry))->toBeFalse();
        expect(array_key_exists('access_token', $entry))->toBeFalse();
    }
});
