<?php

declare(strict_types=1);

namespace App\Module\Core\Infrastructure\ApiPlatform\State\Processor;

use ApiPlatform\Metadata\DeleteOperationInterface;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Module\Core\Domain\Entity\Role;
use Doctrine\ORM\EntityManagerInterface;
use DomainException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

use function assert;

/**
 * @implements ProcessorInterface<Role, null|Role>
 */
final readonly class RoleProcessor implements ProcessorInterface
{
    public function __construct(private EntityManagerInterface $em) {}

    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): ?Role
    {
        assert($data instanceof Role);

        if ($operation instanceof DeleteOperationInterface) {
            try {
                $data->ensureDeletable();
            } catch (DomainException $e) {
                throw new AccessDeniedHttpException($e->getMessage(), $e);
            }
            $this->em->remove($data);
            $this->em->flush();

            return null;
        }

        $this->em->persist($data);
        $this->em->flush();

        return $data;
    }
}
