<?php

namespace App\Services\Analytics;

use App\Models\User;
use App\Models\UserEngagementEvent;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Schema;
use Throwable;

class EngagementLogger
{
    /**
     * @param  array<string, mixed>  $metadata
     */
    public function record(
        ?User $user,
        string $eventType,
        ?string $description = null,
        array $metadata = [],
        ?Model $subject = null,
    ): ?UserEngagementEvent {
        if (! Schema::hasTable('user_engagement_events')) {
            return null;
        }

        try {
            return UserEngagementEvent::query()->create([
                'user_id' => $user?->id,
                'event_type' => $eventType,
                'subject_type' => $subject?->getMorphClass(),
                'subject_id' => $subject?->getKey(),
                'description' => $description,
                'metadata' => $metadata === [] ? null : $metadata,
                'occurred_at' => now(),
            ]);
        } catch (Throwable $exception) {
            report($exception);

            return null;
        }
    }
}
