<?php

declare(strict_types=1);

namespace KupShop\LabelsBundle\Resources\script;

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

class CampaignsToLabelsScript extends Script
{
    protected static $name = 'Migrace kampani do stitku';

    protected static $defaultParameters = [
        'ignore' => ['O', 'B2B', 'R', 'MN'],
    ];

    protected function run(array $arguments)
    {
        foreach (getCampaigns() as $key => $campaign) {
            if (in_array($key, $arguments['ignore'])) {
                continue;
            }

            $labelId = $this->createLabel($campaign['plural'], $key);

            sqlQuery('INSERT IGNORE INTO product_labels_relation (id_label, id_product)
                SELECT 
                    '.$labelId.' as id_label,
                    id as id_product
                FROM products 
                WHERE FIND_IN_SET(:campaign, campaign)', ['campaign' => $key]);

            $this->log('Created new label: '.$campaign['plural']);
        }

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

    private function createLabel(string $label, string $code): int
    {
        $labelId = sqlQueryBuilder()
            ->select('id')
            ->from('labels')
            ->where(Operator::equals(['code' => $code]))
            ->execute()->fetchOne();

        if (!$labelId) {
            $labelId = sqlGetConnection()->transactional(function () use ($code, $label) {
                sqlQueryBuilder()
                    ->insert('labels')
                    ->directValues([
                        'name' => $label,
                        'active' => 'Y',
                        'code' => $code,
                    ])
                    ->execute();

                return (int) sqlInsertId();
            });
        }

        return $labelId;
    }
}

return CampaignsToLabelsScript::class;
