<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\Fixtures\Doctrine;

use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Proxy\InternalProxy;
use Doctrine\Persistence\AbstractManagerRegistry;

/**
 * A one-manager ManagerRegistry over the harness EntityManager.
 *
 * Needed because much of the code under test takes a registry rather than an
 * EntityManager — every `ServiceEntityRepository` in the bundle does, and so
 * does {@see \Ferienpass\CoreBundle\Tenant\TenantContext}.
 */
final class OrmRegistry extends AbstractManagerRegistry
{
    private ?EntityManagerInterface $em = null;

    public function __construct()
    {
        parent::__construct('harness', ['default' => 'connection'], ['default' => 'manager'], 'default', 'default', InternalProxy::class);
    }

    /**
     * The manager arrives after construction: the EntityManager reads its
     * repository factory out of the configuration while constructing, and that
     * factory needs this registry — so the registry has to exist first.
     */
    public function setManager(EntityManagerInterface $em): void
    {
        $this->em = $em;
    }

    protected function getService(string $name): object
    {
        if (null === $this->em) {
            throw new \LogicException('The harness registry has no EntityManager yet.');
        }

        return 'connection' === $name ? $this->em->getConnection() : $this->em;
    }

    protected function resetService(string $name): void
    {
    }
}
