<?php

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Seed;

use Symfony\Component\DependencyInjection\Attribute\AsTaggedItem;

final readonly class SeederMetadata
{
    public function __construct(
        public string $index,
        public int $priority,
    ) {
    }

    public static function fromSeeder(SeederInterface|string $seeder): self
    {
        $reflection = new \ReflectionClass($seeder);
        $attributes = $reflection->getAttributes(AsTaggedItem::class);
        $attribute = $attributes[0] ?? null;

        if (null === $attribute) {
            throw new \LogicException(\sprintf(
                'Seeder "%s" must declare #[AsTaggedItem(index: "...", priority: ...)].',
                $reflection->getName()
            ));
        }

        /** @var AsTaggedItem $instance */
        $instance = $attribute->newInstance();

        if (null === $instance->index || '' === $instance->index) {
            throw new \LogicException(\sprintf(
                'Seeder "%s" must declare a non-empty AsTaggedItem index.',
                $reflection->getName()
            ));
        }

        return new self(
            index: $instance->index,
            priority: $instance->priority ?? 0,
        );
    }
}
