<?php

declare(strict_types=1);

namespace External\ZNZBundle\Resources\script;

use External\ZNZBundle\Synchronizers\BlockDescriptionSynchronizer;
use KupShop\AdminBundle\Util\Script\Script;
use KupShop\ContentBundle\Util\Block;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use Query\Operator;

class ImportProducersTexts extends Script
{
    protected static $name = '[ZNZ] Importovat popisky výrobců';
    protected static $defaultParameters = [
        'file' => __DIR__.'/producers_texts.json',
    ];

    protected function run(array $arguments)
    {
        $blockUtil = ServiceContainer::getService(Block::class);
        $blockDescriptionSynchronizer = ServiceContainer::getService(BlockDescriptionSynchronizer::class);

        $data = json_decode(file_get_contents($arguments['file']), true);

        foreach ($data as $item) {
            $this->log('Processing "'.$item['id'].'": '.$item['name']);

            $producerId = sqlQueryBuilder()
                ->select('id')
                ->from('producers')
                ->where(Operator::equals(['name' => $item['name']]))
                ->execute()->fetchOne();

            if (!$producerId) {
                $this->log('Skipping producer: '.$item['name']);
                continue;
            }

            sqlGetConnection()->transactional(function () use ($blockUtil, $blockDescriptionSynchronizer, $producerId, $item) {
                $rootBlockId = $blockUtil->getRootBlockId('producers', $producerId);

                sqlQueryBuilder()
                    ->delete('blocks')
                    ->where(Operator::equals(['id_root' => $rootBlockId]))
                    ->execute();

                foreach ($item['blocks'] as $lang => $blockData) {
                    $syncItem = [
                        'PopisRich' => json_encode($blockData),
                        'meta' => [
                            'language' => $lang,
                            'translation' => $lang !== 'cs',
                        ],
                    ];

                    $blockDescriptionSynchronizer->updateBlocks('producers', $producerId, $syncItem);
                }
            });
        }
    }
}

return ImportProducersTexts::class;
