<?php

namespace App\MessageHandler;

use App\Entity\AnalyticsEvent;
use App\Entity\AnalyticsUniqId;
use App\Entity\User;
use App\Message\AnalyticsMessage;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler]
class AnalyticsMessageHandler
{
    public function __construct(
        private EntityManagerInterface $em,
    ) {
    }

    public function __invoke(AnalyticsMessage $message): void
    {
        $visitor = $this->em->getRepository(AnalyticsUniqId::class)->findOneBy(['uid' => $message->uid]);
        if (!$visitor) {
            return;
        }

        if ('set_user' === $message->action) {
            $userId = $message->payload['userId'] ?? null;
            if ($userId) {
                $user = $this->em->getRepository(User::class)->find($userId);
                if ($user) {
                    $visitor->setUser($user);
                    $this->em->flush();
                }
            }

            return;
        }

        if ('page_view' === $message->action) {
            $event = new AnalyticsEvent();
            $event->setVisitor($visitor);
            $event->setEventName('page_view');
            $event->setUrl($message->payload['url'] ?? '/');
            $event->setTitle($message->payload['title'] ?? null);
            $event->setReferrer($message->payload['referrer'] ?? null);

            $this->em->persist($event);
            $this->em->flush();
        }
    }
}
