<?php

namespace App\Listeners;

use App\Events\ActivityLogged;
use App\Models\ActivityLog;
use Illuminate\Support\Str;
use Throwable;

class RecordActivityListener
{
    private const MESSAGE_LIMIT = 255;

    public function handle(ActivityLogged $event): void
    {
        try {
            ActivityLog::create([
                'type' => $event->type,
                'message' => Str::limit($event->message, self::MESSAGE_LIMIT, ''),
                'context' => $event->context === [] ? null : $event->context,
                'subject_type' => $event->subject?->getMorphClass(),
                'subject_id' => $event->subject?->getKey(),
                'logged_at' => now(),
            ]);
        } catch (Throwable $e) {
            error_log('Failed to record activity: '.$e->getMessage());
        }
    }
}
