<?php

declare(strict_types=1);

namespace External\HannahBundle\Resources\script;

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

class SAPMappingFixScript extends Script
{
    protected static $name = '[OC] Fix SAP products mapping';
    protected static $defaultParameters = [
        'method' => null,
    ];

    protected function run(array $arguments)
    {
        if (!empty($arguments['method']) && method_exists($this, $arguments['method'])) {
            $this->log('Running', $arguments['method'].'...');
            $this->{$arguments['method']}();
            $this->log('Done');
        }
    }

    private function fixUsersMapping(): void
    {
        $qb = sqlQueryBuilder()
            ->select('*')
            ->from('sap_users');

        $count = 0;
        foreach ($qb->execute() as $item) {
            if (strlen($item['id_sap']) >= 10) {
                continue;
            }

            $sapId = sprintf('%010d', $item['id_sap']);

            $this->log(sprintf('%s -> %s', $item['id_sap'], $sapId));

            // avoid duplicates
            sqlQueryBuilder()
                ->delete('sap_users')
                ->where(Operator::equals(['id_sap' => $sapId, 'id_user' => $item['id_user']]))
                ->execute();

            sqlQueryBuilder()
                ->update('sap_users')
                ->directValues(['id_sap' => $sapId])
                ->where(Operator::equals($item))
                ->execute();

            $count++;
        }

        $this->log('Done; updated: '.$count);
    }

    private function fixProductsMapping(): void
    {
        $qb = sqlQueryBuilder()
            ->select('GROUP_CONCAT(sp.id_sap SEPARATOR \';\') as sap_ids, pv.code, sp.id_product, sp.id_variation')
            ->from('sap_products', 'sp')
            ->join('sp', 'products_variations', 'pv', 'pv.id = sp.id_variation')
            ->where('sp.id_variation IS NOT NULL')
            ->groupBy('sp.id_product, sp.id_variation')
            ->having('COUNT(sp.id_variation) > 1');

        foreach ($qb->execute() as $item) {
            $sapIds = explode(';', $item['sap_ids']);

            $delete = [];
            foreach ($sapIds as $sapId) {
                if ($sapId !== $item['code']) {
                    $delete[] = $sapId;
                }
            }

            if (count($delete) == count($sapIds)) {
                throw new \Exception('Cannot delete all');
            }

            sqlQueryBuilder()
                ->delete('sap_products')
                ->andWhere(Operator::equals(['id_product' => $item['id_product'], 'id_variation' => $item['id_variation']]))
                ->andWhere(Operator::inStringArray($delete, 'id_sap'))
                ->execute();

            $this->progress();
        }
    }
}

return SAPMappingFixScript::class;
