<?php

declare(strict_types=1);

namespace External\ZNZBundle\Resources\script;

use KupShop\AdminBundle\Util\Script\Script;
use Query\Operator;

class FixTranslatedBlocksScript extends Script
{
    protected static $name = '[ZNZ] Fix translated blocks';

    protected function run(array $arguments)
    {
        $qb = sqlQueryBuilder()
            ->select('b.id, b.json_content as data, bt.id as id_translation, bt.json_content as translated_data')
            ->from('blocks', 'b')
            ->join('b', 'blocks_translations', 'bt', 'bt.id_block = b.id')
            ->where(Operator::like(['b.json_content' => '%legacy%']));

        foreach ($qb->execute() as $item) {
            $data = json_decode($item['data'] ?: '', true) ?: [];
            $translatedData = json_decode($item['translated_data'] ?: '', true) ?: [];

            if (!($translatedData = static::fixBlockIds($data, $translatedData))) {
                continue;
            }

            sqlQueryBuilder()
                ->update('blocks_translations')
                ->directValues(
                    [
                        'json_content' => json_encode($translatedData),
                    ]
                )
                ->where(Operator::equals(['id' => $item['id_translation']]))
                ->execute();
        }
    }

    public static function fixBlockIds(array $data, array $translatedData): ?array
    {
        if (empty($data[0]) || empty($translatedData[0])) {
            return null;
        }

        if ($data[0]['type'] !== $translatedData[0]['type']) {
            return null;
        }

        if ($data[0]['id'] === $translatedData[0]['id']) {
            return null;
        }

        $translatedData[0]['id'] = $data[0]['id'];

        return $translatedData;
    }
}

return FixTranslatedBlocksScript::class;
