<?php

namespace AutoAdmin\Bundle\Core\EventListener;

use AutoAdmin\Bundle\Content\Model\SequencedInterface;
use Doctrine\ORM\Event\LoadClassMetadataEventArgs;
use Doctrine\ORM\Mapping\ClassMetadata;

class OrderBySequenceListener
{
    public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs): void
    {
        $classMetadata = $eventArgs->getClassMetadata();
        $reflectionClass = $classMetadata->getReflectionClass();

        if (!$reflectionClass) {
            return;
        }

        foreach ($classMetadata->associationMappings as &$association) {
            if (
                $association['type'] === ClassMetadata::ONE_TO_MANY
                && isset($association['targetEntity'])
                && is_subclass_of($association['targetEntity'], SequencedInterface::class)
                && empty($association['orderBy'])
            ) {
                $association['orderBy'] = ['sequence' => 'ASC'];
            }
        }
    }
}
