<?php

declare(strict_types=1);

namespace Gls\GlsPoland\Configuration\Initializer;

use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain as LegacyDriverChain;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
use Doctrine\Persistence\Mapping\Driver\MappingDriverChain;

/**
 * @internal
 */
final class DoctrineMappingsInitializer implements ConfigurationInitializerInterface
{
    private $entityManager;
    private $module;

    public function __construct(EntityManagerInterface $entityManager, \Module $module)
    {
        $this->entityManager = $entityManager;
        $this->module = $module;
    }

    public function init(): void
    {
        $mappingDriver = $this->entityManager
            ->getConfiguration()
            ->getMetadataDriverImpl();

        assert($mappingDriver instanceof MappingDriverChain || $mappingDriver instanceof LegacyDriverChain);

        if (array_key_exists('Gls\\GlsPoland\\Entity', $mappingDriver->getDrivers())) {
            return;
        }

        $driver = new AnnotationDriver(new AnnotationReader(), [$this->module->getLocalPath() . 'src/Entity/']);
        $mappingDriver->addDriver($driver, 'Gls\\GlsPoland\\Entity');
    }
}
