<?php

namespace App\Listeners;

use App\Events\DocumentGenerated;
use Illuminate\Support\Facades\Log;

class LogDocumentGenerated
{
    public function handle(DocumentGenerated $event): void
    {
        $doc = $event->document;
        Log::info('Document generated', [
            'uuid' => $doc->uuid,
            'template_id' => $doc->template_id,
            'template_version' => $doc->template_version,
            'user_id' => $doc->user_id,
            'path' => $doc->path,
        ]);

        try {
            \DB::table('document_generation_logs')->insert([
                'document_id' => $doc->id,
                'user_id' => $doc->user_id,
                'ip' => request()?->ip(),
                'user_agent' => substr((string) request()?->userAgent(), 0, 255),
                'context' => json_encode([
                    'template_id' => $doc->template_id,
                    'template_version' => $doc->template_version,
                ]),
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        } catch (\Throwable $e) {
            Log::warning('Failed to persist document generation log', [
                'document_id' => $doc->id,
                'error' => $e->getMessage(),
            ]);
        }
    }
}
