<?php

declare(strict_types=1);

namespace App\Services\Audit;

use Illuminate\Support\Facades\DB;

/**
 * Запись в tenant_operations_log — журнал тенант-уровневых мутаций
 * вне сделок (проекты, API-ключи, исходящий webhook URL, и т.п.).
 *
 * Hash-chain trigger audit_chain_hash() автоматически заполняет log_hash;
 * append-only защита — audit_block_mutation (UPDATE/DELETE заблокированы).
 *
 * Канонические event-strings (расширяемо):
 *   project.created, project.updated, project.deleted,
 *   project.bulk_paused, project.bulk_resumed, project.bulk_limit_changed,
 *   api_key.regenerated,
 *   webhook_settings.updated, webhook_settings.disabled.
 */
final class OperationsLogger
{
    /**
     * @param  array<string, mixed>|null  $payloadBefore
     * @param  array<string, mixed>|null  $payloadAfter
     */
    public function record(
        int $tenantId,
        ?int $userId,
        string $entityType,
        ?int $entityId,
        string $event,
        ?array $payloadBefore,
        ?array $payloadAfter,
        ?string $ip,
        ?string $userAgent,
    ): void {
        DB::table('tenant_operations_log')->insert([
            'tenant_id' => $tenantId,
            'user_id' => $userId,
            'entity_type' => $entityType,
            'entity_id' => $entityId,
            'event' => $event,
            'payload_before' => $payloadBefore !== null
                ? json_encode($payloadBefore, JSON_UNESCAPED_UNICODE)
                : null,
            'payload_after' => $payloadAfter !== null
                ? json_encode($payloadAfter, JSON_UNESCAPED_UNICODE)
                : null,
            'ip_address' => $ip,
            'user_agent' => $userAgent,
            'created_at' => now(),
        ]);
    }
}
