<?php
declare(strict_types=1);

namespace App\State\Processor\Access;

use ApiPlatform\Metadata\Delete;
use ApiPlatform\State\ProcessorInterface;
use App\Entity\Access\Access;
use App\Service\Access\Utils as AccessUtils;
use App\Service\Core\ContactPointUtils;
use Doctrine\ORM\EntityManagerInterface;
use RuntimeException;
use Symfony\Bundle\SecurityBundle\Security;
use ApiPlatform\Metadata\Operation;

/**
 * Classe AdminAccessProcessor qui est un custom dataPersister gérant la resource AdminAccess
 */
class AdminAccessProcessor implements ProcessorInterface
{
    public function __construct(
        private Security $security,
        private EntityManagerInterface $entityManager,
        private AccessUtils $accessUtils,
        private ContactPointUtils $contactPointUtils
    )
    { }

    /**
     * @param mixed $data
     * @param Operation $operation
     * @param mixed[] $uriVariables
     * @param mixed[] $context
     * @return void
     */
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): void
    {
        if($operation instanceof Delete){
            throw new RuntimeException('not supported', 500);
        }

        /** @var Access $access */
        $access = $this->security->getUser();

        $administrator = $this->accessUtils->findAdminFor($access->getOrganization());
        if(!$administrator){
            throw new RuntimeException('administrator_not_found', 404);
        }

        $contactPoint = $this->contactPointUtils->getPersonContactPointPrincipal($administrator);
        if(!$contactPoint){
            throw new RuntimeException('administrator_contact_point_not_found', 404);
        }

        $contactPoint->setEmail($data->getEmail());
        $this->entityManager->flush();
    }
}
