<?php

namespace App\Services;

use App\Models\AnalyticsEvent;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Throwable;

class AnalyticsTracker
{
    public function track(
        Request $request,
        string $eventName,
        ?string $entityType = null,
        ?int $entityId = null,
        array $metadata = []
    ): void {
        try {
            AnalyticsEvent::create([
                'uuid' => (string) Str::uuid(),
                'user_id' => $request->user()?->id,
                'session_id' => $request->hasSession() ? $request->session()->getId() : null,
                'event_name' => $eventName,
                'entity_type' => $entityType,
                'entity_id' => $entityId,
                'url' => Str::limit($request->fullUrl(), 1000, ''),
                'referrer' => Str::limit((string) $request->headers->get('referer'), 1000, ''),
                'ip_hash' => $request->ip() ? hash('sha256', config('app.key').'|'.$request->ip()) : null,
                'user_agent' => Str::limit((string) $request->userAgent(), 500, ''),
                'metadata' => $metadata,
                'occurred_at' => now(),
            ]);
        } catch (Throwable $exception) {
            Log::debug('Analytics tracking skipped', [
                'event' => $eventName,
                'message' => $exception->getMessage(),
            ]);
        }
    }
}
