<?php

namespace App\MessageHandler;

use App\Entity\AppLog;
use App\Message\AppLogMessage;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler]
class AppLogMessageHandler
{
    public function __construct(
        private EntityManagerInterface $em,
        private UserRepository $userRepository,
        #[Autowire('%env(APP_SECRET)%')] private string $hmacSecret,
    ) {
    }

    public function __invoke(AppLogMessage $message): void
    {
        $user = null !== $message->userId ? $this->userRepository->find($message->userId) : null;

        $log = new AppLog(
            $message->method,
            $message->url,
            $message->route,
            $message->action,
            $this->hmacSecret,
            $user,
            $message->ip,
        );

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