<?php

namespace App\Serp\Operations;

use App\Models\SerpOperationAudit;
use App\Models\User;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

final class OperationAuditLogger
{
    public function record(string $action, array $context = [], ?User $actor = null, ?string $correlationId = null): void
    {
        $safe = array_intersect_key($context, array_flip(['check_ulid', 'provider', 'mode', 'task_reference', 'attempt', 'duration_ms', 'result_count', 'error_category', 'cost_micros', 'reason']));
        $id = $correlationId ?: Str::uuid()->toString();
        SerpOperationAudit::create(['actor_user_id' => $actor?->id, 'action' => $action, 'correlation_id' => $id, 'context' => $safe]);
        Log::info('serp_operation.'.$action, ['correlation_id' => $id] + $safe);
    }
}
