<?php

declare(strict_types=1);

namespace App\Service\Access;

use App\ApiResources\Access\AdminAccess;
use App\Entity\Organization\Organization;
use App\Service\Core\ContactPointUtils;
use App\Test\Service\Access\AdminAccessUtilsTest;

/**
 * Class AdminAccessUtils : Service contenant les manipulations associés à la ressource AdminAccess.
 */
class AdminAccessUtils
{
    public function __construct(
        private Utils $accessUtils,
        private ContactPointUtils $contactPointUtils,
    ) {
    }

    /**
     * Renvoie l'objet AdminAccess initialisé par rapport à l'organization passée en paramètre.
     *
     * @throws \Exception
     *
     * @see AdminAccessUtilsTest::testGetAdminAccess()
     */
    public function getAdminAccess(Organization $organization): ?AdminAccess
    {
        $administrator = $this->accessUtils->findAdminFor($organization);
        if (!$administrator) {
            return null;
        }

        $contactPoint = $this->contactPointUtils->getPersonContactPointPrincipal($administrator);
        if (!$contactPoint) {
            return null;
        }

        $adminAccess = new AdminAccess();
        $adminAccess
            ->setOrganizationId($organization->getId())
            ->setId($administrator->getId())
            ->setOrganizationId($organization->getId())
            ->setUsername($administrator->getPerson()->getUserIdentifier())
            ->setEmail($contactPoint->getEmail())
        ;

        return $adminAccess;
    }
}
