<?php

declare(strict_types=1);

namespace External\PompoBundle\Resources\script;

use External\PompoBundle\DataGo\Synchronizer\ProductSynchronizer;
use External\PompoBundle\DataGo\Util\DataGoApi;
use KupShop\AdminBundle\Util\Script\Script;
use KupShop\CatalogBundle\Product\ProductFinder;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

class DataGoUpdateScript extends Script
{
    protected static $name = '[DataGo] Update products script';
    protected static $defaultParameters = [
        'file' => 'produkty-1363.csv',
        'updateParameters' => [],
    ];

    protected function run(array $arguments)
    {
        $api = ServiceContainer::getService(DataGoApi::class);
        $synchronizer = ServiceContainer::getService(ProductSynchronizer::class);
        $productFinder = ServiceContainer::getService(ProductFinder::class);

        $data = $api->fetchCSVData(
            $arguments['file']
        );

        sqlGetConnection()->getConfiguration()->setSQLLogger();

        foreach ($data as $item) {
            if (!($productId = $productFinder->getProductIdByCode($item['cislo-zbozi']))) {
                continue;
            }

            $synchronizer->processParameters($productId, $item, $arguments['updateParameters'] ?? []);

            $this->progress();
        }

        $this->log('Update done');
    }
}

return DataGoUpdateScript::class;
