<?php

declare(strict_types=1);

namespace External\FlexiBeeBundle\SynchronizationRegister;

use External\FlexiBeeBundle\Synchronizers\OrderSynchronizer;
use External\FlexiBeeBundle\Synchronizers\PriceListSynchronizer;
use External\FlexiBeeBundle\Synchronizers\PriceSynchronizer;
use External\FlexiBeeBundle\Synchronizers\ProductSynchronizer;
use External\FlexiBeeBundle\Synchronizers\StoreSynchronizer;
use External\FlexiBeeBundle\Synchronizers\SupplySynchronizer;
use External\FlexiBeeBundle\Synchronizers\UserSynchronizer;
use External\FlexiBeeBundle\Util\FlexiBeeConfiguration;
use External\FlexiBeeBundle\Util\FlexiBeeUtil;
use KupShop\SynchronizationBundle\Synchronization\Job;
use KupShop\SynchronizationBundle\Synchronization\SynchronizationRegisterInterface;
use Symfony\Component\Console\Output\OutputInterface;

class FlexiBeeSynchronizationRegister implements SynchronizationRegisterInterface
{
    private FlexiBeeConfiguration $configuration;
    private FlexiBeeUtil $util;

    public function __construct(FlexiBeeConfiguration $configuration, FlexiBeeUtil $util)
    {
        $this->configuration = $configuration;
        $this->util = $util;
    }

    public function getJobs(): iterable
    {
        // hlavni synchronizacni thread
        yield Job::create('FlexiBee::main', fn (OutputInterface $output) => $this->synchronize($output))
            ->everyMinute(5);
        // zalozeni skladu - nepotrebuju to spoustet furt, tak to oddelim od toho hlavniho threadu
        yield Job::create('FlexiBee::stores', fn () => $this->util->synchronize([StoreSynchronizer::getType()]))
            ->hourly();
    }

    private function synchronize(OutputInterface $output): void
    {
        // Tady mam serazene synchronizace tak, jak by meli jit po sobe
        $synchronizers = [
            UserSynchronizer::getType(),
            OrderSynchronizer::getType(),
            ProductSynchronizer::getType(),
            SupplySynchronizer::getType(),
            PriceSynchronizer::getType(),
            PriceListSynchronizer::getType(),
        ];

        // Projdu serazene typy synchronizaci
        foreach ($synchronizers as $synchronizer) {
            // Pokud neni typ povoleny, tak skipuju
            if (!in_array($synchronizer, $this->configuration->getEnabledSynchronizerTypes())) {
                continue;
            }

            $output->writeln(sprintf('[FlexiBee] Running synchronization: %s...', $synchronizer));
            $this->util->synchronize([$synchronizer]);
            $output->writeln(sprintf('[FlexiBee] Completed synchronization: %s', $synchronizer));
        }
    }
}
