<?php

use App\Models\AuditLog;
use App\Models\User;
use App\Models\WorkspaceMembership;
use App\Services\Auth\ManagedEnvironmentMembershipManager;
use App\Support\Audit\AuditActionId;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('writes audit logs for environment access scope grant and remove without sensitive fields', function () {
    [$actor, $tenant] = createUserWithTenant(role: 'owner');
    $member = User::factory()->create();
    WorkspaceMembership::factory()->create([
        'workspace_id' => (int) $tenant->workspace_id,
        'user_id' => (int) $member->getKey(),
        'role' => 'readonly',
    ]);

    $manager = app(ManagedEnvironmentMembershipManager::class);

    $membership = $manager->addMember($tenant, $actor, $member, 'readonly');
    $manager->removeMember($tenant, $actor, $membership);

    $actions = AuditLog::query()
        ->where('managed_environment_id', $tenant->getKey())
        ->whereIn('action', [
            AuditActionId::ManagedEnvironmentAccessScopeGrant->value,
            AuditActionId::ManagedEnvironmentAccessScopeRemove->value,
        ])
        ->pluck('action')
        ->all();

    expect($actions)->toContain(AuditActionId::ManagedEnvironmentAccessScopeGrant->value);
    expect($actions)->toContain(AuditActionId::ManagedEnvironmentAccessScopeRemove->value);

    $metadata = AuditLog::query()
        ->where('managed_environment_id', $tenant->getKey())
        ->whereIn('action', [
            AuditActionId::ManagedEnvironmentAccessScopeGrant->value,
            AuditActionId::ManagedEnvironmentAccessScopeRemove->value,
        ])
        ->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();
    }
});
