<?php

namespace App\Listeners;

use App\Events\ExceptionLogged;
use App\Events\ExceptionOccurred;
use App\Models\Log;

class LogExceptionToDatabase
{
    public function handle(ExceptionOccurred $event): void
    {
        // Truncate the message to prevent database errors
        $message = strlen($event->message) > 255
            ? substr($event->message, 0, 252).'...'
            : $event->message;

        try {
            $log = Log::create([
                'level' => $event->level,
                'message' => $message,
                'context' => [
                    'exception_class' => get_class($event->exception),
                    'file' => $event->exception->getFile(),
                    'line' => $event->exception->getLine(),
                    'trace' => $event->exception->getTraceAsString(),
                    ...$event->context,
                ],
            ]);

            ExceptionLogged::dispatch($log);
        } catch (\Exception $e) {
            // Prevent infinite recursion by not logging this exception
            // Optionally log to file or other non-database destination
            error_log('Failed to log exception to database: '.$e->getMessage());
        }
    }
}
