<?php

namespace App\Service;

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

class AuditService
{
    public function __construct(
        private EntityManagerInterface $em,
        private Security $security,
        private RequestStack $requestStack,
    ) {
    }

    /** @param array<string, mixed> $data */
    public function log(string $action, string $entityType, ?int $entityId = null, array $data = []): void
    {
        $log = new AuditLog($action, $entityType, $entityId);
        $log->setData($data);

        $user = $this->security->getUser();
        if ($user) {
            $log->setPerformedBy($user->getUserIdentifier());
        }

        $request = $this->requestStack->getCurrentRequest();
        if ($request) {
            $log->setIpAddress($request->getClientIp());
        }

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