<?php

declare(strict_types=1);

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

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Module\Core\Domain\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

use function assert;

/**
 * @implements ProcessorInterface<User, User>
 */
final readonly class UserRbacProcessor implements ProcessorInterface
{
    public function __construct(
        private EntityManagerInterface $em,
        private Security $security,
    ) {}

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

        // Defense-in-depth: a user may never edit their OWN RBAC assignment
        // through this endpoint, even with core.users.manage — this prevents
        // self-escalation if the permission is ever delegated to a non-admin.
        $current = $this->security->getUser();
        if ($current instanceof User && $current->getId() === $data->getId()) {
            throw new AccessDeniedHttpException('You cannot edit your own RBAC assignment.');
        }

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

        return $data;
    }
}
