<?php

namespace KupShop\POSBundle\Resources\script;

use KupShop\AdminBundle\Util\Script\Script;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\POSBundle\Util\PosEntity;
use KupShop\POSBundle\Util\PosWarehouseUtil;
use KupShop\WarehouseBundle\Entity\StoreItem;
use KupShop\WarehouseBundle\Util\Logger;
use KupShop\WarehouseBundle\Util\StoreItemWorker;

class PosCorrectWarehouseIssue extends Script
{
    private PosWarehouseUtil $posWarehouseUtil;
    private PosEntity $posEntity;
    private StoreItemWorker $storeItemWorker;
    /** @var Logger */
    private $logger;

    protected static $name = 'Opravit chybu na skladu, která vznikla z pokladny';

    protected static $defaultParameters = [
        'ean' => '123456789',
        'pos' => 1,
        'pieces' => 1,
        'execute' => false,
    ];

    public function __construct()
    {
        $this->posWarehouseUtil = ServiceContainer::getService(PosWarehouseUtil::class);
        $this->posEntity = ServiceContainer::getService(PosEntity::class);
        $this->storeItemWorker = ServiceContainer::getService(StoreItemWorker::class);
        $this->logger = ServiceContainer::getService(Logger::class);
    }

    protected function run(array $arguments)
    {
        $this->posEntity->createFromDB($arguments['pos']);

        $productRow = $this->storeItemWorker->checkProductByEanAndLocation($arguments['ean']);
        $availablePositions = $this->posWarehouseUtil->searchProductInLocations($productRow['id_product'], $productRow['id_variation'] ?? null, $this->posEntity);

        if ($arguments['execute']) {
            $pieces = $arguments['pieces'];
            $old_position = $availablePositions[0]['id_position'];
            $storeItem = new StoreItem([
                'id_product' => $availablePositions[0]['id_product'],
                'id_variation' => $availablePositions[0]['id_variation'],
                'id_product_batch' => $availablePositions[0]['id_product_batch'],
            ]);

            sqlGetConnection()->transactional(function () use ($storeItem, $pieces, $old_position, &$result) {
                $this->storeItemWorker->updateOnPosition($storeItem, $old_position, $pieces);
                $result = $this->logger->logProductMove($storeItem, $pieces, $old_position, null);
            });
            $this->log("Pozice aktualizována: {$arguments['ean']}");
        } else {
            $this->log("Dostupná pozice pro produkt s eanem: {$arguments['ean']}");
            $this->log("
                - ID: {$availablePositions[0]['id_position']} \n
                - Kusy: {$availablePositions[0]['pieces']} \n
                - Šarže: {$availablePositions[0]['id_product_batch']}");
        }
    }
}

return PosCorrectWarehouseIssue::class;
