<?php


namespace Shared\RightManagement\EventSubscriber;


use ApiPlatform\Core\EventListener\EventPriorities;
use Doctrine\ORM\EntityManagerInterface;
use Shared\Authentication\Entity\User;
use Shared\RightManagement\Entity\AdvancedGroupRight;
use Shared\RightManagement\Entity\AdvancedUserRight;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Webapp\Core\Entity\UserGroup;

class UnusedRightPurgerEventSubscriber implements EventSubscriberInterface
{

    private EntityManagerInterface $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::VIEW => ['updateAdvancedRight', EventPriorities::PRE_WRITE],
        ];
    }

    public function updateAdvancedRight(ViewEvent $event): void
    {
        $result = $event->getControllerResult();
        $method = $event->getRequest()->getMethod();
        if (!$result instanceof User && !$result instanceof UserGroup || Request::METHOD_DELETE !== $method) {
            return;
        }
        $isUser = $result instanceof User;

        $rights = $this->entityManager->getRepository($isUser ? AdvancedUserRight::class : AdvancedGroupRight::class)->findBy([
            $isUser ? 'userId' : 'groupId' => $result->getId()
        ]);
        foreach ($rights as $right) {
            $this->entityManager->remove($right);
        }


    }
}
