<?php

namespace App\Logger;

use App\Entity\Account;
use App\Entity\AuditLog;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\RequestStack;

class AppLogger
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly Security $security,
        private readonly RequestStack $requestStack
    ) {}

    public function record(string $type, string $message): void
    {
        $user = $this->security->getUser();
        if (!$user instanceof Account) {
            return;
        }

        $request = $this->requestStack->getCurrentRequest();
        $path = $request ? $request->getRequestUri() : 'CLI/Internal';
        $userAgent = $request ? $request->headers->get('user-agent') : 'CLI';

        // Création de l'objet immuable via le constructeur
        $log = new AuditLog($user, $type, $message, $path, $userAgent);

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