<?php

declare(strict_types=1);

namespace Gls\GlsPoland\Doctrine\ORM\EntityListener;

use Doctrine\ORM\Event\LoadClassMetadataEventArgs;
use Doctrine\ORM\Mapping\ClassMetadata;

/**
 * @internal
 */
final class PrefixTableListener
{
    private $prefix;

    public function __construct(string $dbPrefix)
    {
        $this->prefix = $dbPrefix;
    }

    public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs): void
    {
        $classMetadata = $eventArgs->getClassMetadata();
        if (!str_starts_with($entityClassName = $classMetadata->getName(), 'Gls\\GlsPoland\\Entity\\')) {
            return;
        }

        if ($classMetadata->rootEntityName === $entityClassName || !$classMetadata->isInheritanceTypeSingleTable()) {
            $classMetadata->setPrimaryTable([
                'name' => $this->prefix . $classMetadata->getTableName(),
            ]);
        }

        foreach ($classMetadata->getAssociationMappings() as $fieldName => $mapping) {
            if (ClassMetadata::MANY_TO_MANY === $mapping['type'] && $mapping['isOwningSide']) {
                $mappedTableName = $mapping['joinTable']['name'];
                $classMetadata->associationMappings[$fieldName]['joinTable']['name'] = $this->prefix . $mappedTableName;
            }
        }
    }
}
