<?php

declare(strict_types=1);

namespace External\SprintBundle\SynchronizationRegister;

use External\MSSQLBundle\Util\MoneyConnection;
use External\SprintBundle\Synchronizers\OrderToHeliosSynchronizer;
use External\SprintBundle\Util\HeliosUtil;
use KupShop\SynchronizationBundle\Synchronization\Job;
use KupShop\SynchronizationBundle\Synchronization\SynchronizationRegisterInterface;
use Symfony\Component\Console\Output\OutputInterface;

class HeliosSynchronizationRegister implements SynchronizationRegisterInterface
{
    private HeliosUtil $util;

    public function __construct(HeliosUtil $util, private MoneyConnection $moneyConnection)
    {
        $this->util = $util;
    }

    public function getJobs(): iterable
    {
        // hlavni synchronizacni thread
        yield Job::create('Helios::main', fn (OutputInterface $output) => $this->synchronize($output))
            ->everyMinute(1);
    }

    private function synchronize(OutputInterface $output): void
    {
        // Tady mam serazene synchronizace tak, jak by meli jit po sobe
        $synchronizers = [
            OrderToHeliosSynchronizer::getType(),
        ];
        try {
            // Projdu serazene typy synchronizaci
            foreach ($synchronizers as $synchronizer) {
                $output->writeln(sprintf('[Helios] Running synchronization: %s...', $synchronizer));
                $this->util->synchronize($synchronizer);
                $output->writeln(sprintf('[Helios] Completed synchronization: %s', $synchronizer));
            }
        } catch (\Exception $exception) {
            $this->moneyConnection->close();
        } finally {
            $this->moneyConnection->close();
        }
    }
}
