<?php

declare(strict_types=1);

use App\Models\AuditLog;
use App\Models\User;
use App\Models\Workspace;
use App\Services\Audit\WorkspaceAuditLogger;

it('redacts secret-like fields in workspace audit metadata', function (): void {
    $workspace = Workspace::factory()->create();
    $actor = User::factory()->create();

    /** @var WorkspaceAuditLogger $logger */
    $logger = app(WorkspaceAuditLogger::class);

    $logger->log(
        workspace: $workspace,
        action: 'test.redaction',
        context: [
            'metadata' => [
                'access_token' => 'super-secret-token',
                'client_secret' => 'super-secret-secret',
                'passwordMinimumLength' => 12,
                'nested' => [
                    'Authorization' => 'Bearer abc.def.ghi',
                    'safe' => 'ok',
                ],
            ],
        ],
        actor: $actor,
        status: 'success',
        resourceType: 'workspace',
        resourceId: (string) $workspace->getKey(),
    );

    $log = AuditLog::query()
        ->where('workspace_id', (int) $workspace->getKey())
        ->where('action', 'test.redaction')
        ->latest('id')
        ->firstOrFail();

    expect($log->metadata['access_token'] ?? null)->toBe('[REDACTED]');
    expect($log->metadata['client_secret'] ?? null)->toBe('[REDACTED]');
    expect($log->metadata['passwordMinimumLength'] ?? null)->toBe(12);
    expect($log->metadata['nested']['Authorization'] ?? null)->toBe('[REDACTED]');
    expect($log->metadata['nested']['safe'] ?? null)->toBe('ok');
});
