<?php

/*
 * This file is part of the Serenity 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 Serenity\CoreBundle\Seed\Command;

use Serenity\CoreBundle\Seed\SeedRunner;
use Serenity\CoreBundle\Seed\SeedScopeProviderInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;

#[AsMessageHandler()]
readonly class SeedCommandHandler
{
    public function __construct(
        #[Autowire('%serenity_saas%')]
        private bool $saasEnabled,
        private SeedRunner $runner,
        #[Autowire(service: SeedScopeProviderInterface::class, lazy: true)]
        private ?SeedScopeProviderInterface $scopes = null,
    ) {
    }

    public function __invoke(SeedCommand $command): void
    {
        // SaaS OFF => GLOBAL or Saas ON => Global ON, pas associé à un saasIdentifier
        if (!$this->saasEnabled || $command->payload->global) {
            $this->runner->run($command->payload, null);

            return;
        }

        if (!$this->scopes) {
            throw new \LogicException('SeedScopeProviderInterface is required when SaaS is enabled.');
        }

        foreach ($this->scopes->iterateForSeeding($command->payload) as $saasIdentifier) {
            $this->runner->run($command->payload, $saasIdentifier);
        }
    }
}
