<?php

declare(strict_types=1);

use App\Models\Tenant;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;

uses(DatabaseTransactions::class);

it('api_key.regenerated logged with key_prefix only (NO plain key)', function () {
    $tenant = Tenant::factory()->create();
    $user = User::factory()->create(['tenant_id' => $tenant->id]);
    $this->actingAs($user);
    DB::statement('SET app.current_tenant_id = '.$tenant->id);

    $r = $this->postJson('/api/api-keys/regenerate');
    $r->assertStatus(201);

    $row = DB::table('tenant_operations_log')
        ->where('event', 'api_key.regenerated')
        ->where('tenant_id', $tenant->id)
        ->latest('id')
        ->first();

    expect($row)->not->toBeNull()
        ->and($row->entity_type)->toBe('api_key')
        ->and((int) $row->user_id)->toBe($user->id);

    $payloadAfter = json_decode($row->payload_after, true);
    expect($payloadAfter['key_prefix'] ?? null)->not->toBeNull()
        ->and(strlen($payloadAfter['key_prefix']))->toBeLessThan(20);

    // NO plain key allowed in the log:
    expect(json_encode($payloadAfter))->not->toContain('plain_key')
        ->and(json_encode($payloadAfter))->not->toContain('secret');
});
