<?php
declare(strict_types=1);

namespace App\DataPersister\Access;

use ApiPlatform\Core\DataPersister\ContextAwareDataPersisterInterface;
use App\Entity\Access\Access;
use App\Service\Access\Utils as AccessUtils;
use App\Service\Core\ContactPointUtils;
use Exception;
use App\ApiResources\Access\AdminAccess;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Security;


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

    public function supports($data, array $context = []): bool
    {
        return $data instanceof AdminAccess;
    }

    /**
     * @param AdminAccess $data
     * @param array $context
     * @return void|null
     */
    public function persist($data, array $context = [])
    {
        /** @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();
    }

    public function remove($data, array $context = [])
    {
        throw new \RuntimeException('not supported', 500);
    }
}
