<?php

namespace KupShop\CatalogBundle\Resources\upgrade;

use KupShop\CatalogBundle\Search\FulltextElastic;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;

class FullTextUpgrade extends \UpgradeNew
{
    public function check_FullTextCreateAlias()
    {
        return $this->checkDataMigration(19);
    }

    /** FullTextSearch - alias old indices as current */
    public function upgrade_FullTextCreateAlias()
    {
        /** @var FulltextElastic $fulltext */
        $fulltext = ServiceContainer::getService(FulltextElastic::class);

        $sUrl = $fulltext->getServerUrl();
        $prefix = str_replace('_current', '', $fulltext->getIndexPrefix());

        if (!str_starts_with($sUrl, 'http')) {
            $sUrl = "http://{$sUrl}";
        }

        foreach (FulltextElastic::INDEX_TYPES as $t) {
            $req = [
                'actions' => [
                    'add' => [
                        'index' => "{$prefix}*.{$t}",
                        'alias' => $fulltext->getIndex($t),
                    ],
                ],
            ];
            try {
                $fulltext->curlInitSession("{$sUrl}/_aliases", 'POST', json_encode($req));
            } catch (\Exception $e) {
            }
        }

        $this->commitDataMigration(19);

        $this->upgradeOK();
    }

    public function check_FullTextSynonymsToDB()
    {
        return $this->checkDataMigration(20);
    }

    /** FullTextSearch - migrate synonyms to dbcfg */
    public function upgrade_FullTextSynonymsToDB()
    {
        /** @var FulltextElastic $fulltext */
        $fulltext = ServiceContainer::getService(FulltextElastic::class);

        $synonyms = $fulltext->loadSynonymsFromIndex() ?? [];

        var_dump('Synonyms: ', count($synonyms));

        $fulltext->saveSynonyms($synonyms);

        $this->commitDataMigration(20);

        $this->upgradeOK();
    }
}
