<?php

namespace App\Logger;

use App\Entity\AuditLog;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsEntityListener;
use Doctrine\ORM\Event\PrePersistEventArgs;
use Doctrine\ORM\Events;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Symfony\Bundle\SecurityBundle\Security;

#[AsEntityListener(event: Events::preUpdate, method: 'preUpdate', entity: AuditLog::class)]
#[AsEntityListener(event: Events::preRemove, method: 'preRemove', entity: AuditLog::class)]
#[AsEntityListener(event: Events::prePersist, method: 'prePersist', entity: AuditLog::class)]

class AuditLogSecurityListener
{
    public function __construct(
        private Security $security
    ) {}

    // Exécuté lors de la CRÉATION initiale du log
    public function prePersist(AuditLog $log, PrePersistEventArgs $event): void
    {
        $log->generateSignature();
    }

    public function preUpdate(AuditLog $log, PreUpdateEventArgs $event): void
    {
        if (!$this->security->isGranted('ROLE_ROOT')) {
            throw new \LogicException("AuditLog est immuable : modification interdite.");
        }
        $log->generateSignature();
    }

    public function preRemove(AuditLog $log): void
    {
        if (!$this->security->isGranted('ROLE_ROOT')) {
            throw new \LogicException("AuditLog est protégé : suppression interdite.");
        }
    }
}
