<?php

declare(strict_types=1);

namespace External\PompoBundle\Resources\script;

use External\PompoBundle\DRS\Synchronizer\PriceSynchronizer;
use External\PompoBundle\DRS\Synchronizer\StockSynchronizer;
use External\PompoBundle\DRS\Synchronizer\SynchronizerInterface;
use External\PompoBundle\DRS\Synchronizer\UserSynchronizer;
use External\PompoBundle\Util\PompoUtil;
use KupShop\AdminBundle\Util\Script\Script;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

class DRSSynchronizationScript extends Script
{
    protected static $name = '[DRS] Run synchronization';
    protected static $defaultParameters = [
        'type' => null,
        'mode' => 0,
        'synchronizeActionPrices' => false,
        'synchronizeAllUsersFromDrs' => false,
        'synchronizeUsersFromDRSFromTimeStamp' => false,
        'synchronizeDRSStockFull' => false,
    ];

    protected function run(array $arguments)
    {
        sqlGetConnection()->getConfiguration()->setSQLLogger();

        if ($arguments['synchronizeDRSStockFull'] ?? false) {
            $this->log('Synchronizing action DRS full stock...');

            $stockSynchronizer = ServiceContainer::getService(StockSynchronizer::class);
            $stockSynchronizer->syncFullStock();

            $this->log('Done');

            return;
        }

        if ($arguments['synchronizeActionPrices'] ?? false) {
            $this->log('Synchronizing action prices...');

            $priceSynchronizer = ServiceContainer::getService(PriceSynchronizer::class);
            $priceSynchronizer->processActionPrices(true);

            $this->log('Done');

            return;
        }

        if ($arguments['synchronizeAllUsersFromDrs'] ?? false) {
            $this->log('Synchronizing users...');

            $userSynchronizer = ServiceContainer::getService(UserSynchronizer::class);
            $userSynchronizer->setMode(SynchronizerInterface::MODE_FULL);
            $userSynchronizer->processFromDRS(null, null);

            $this->log('Done');

            return;
        }

        if ($arguments['synchronizeUsersFromDRSFromTimeStamp'] ?? false) {
            $this->log('Synchronizing users...');

            // 134867683095
            $userSynchronizer = clone ServiceContainer::getService(UserSynchronizer::class);
            $userSynchronizer->setMode(SynchronizerInterface::MODE_FULL);
            $userSynchronizer->processFromDRS((int) $arguments['synchronizeUsersFromDRSFromTimeStamp'], null);

            $this->log('Done');

            return;
        }

        if (!($arguments['type'] ?? false)) {
            $this->log('You must specify type!');

            return;
        }

        $pompoUtil = ServiceContainer::getService(PompoUtil::class);

        $this->log('Running...');

        $pompoUtil->synchronizeDRS([$arguments['type']], $arguments['mode']);

        $this->log('Done');
    }
}

return DRSSynchronizationScript::class;
