<?php

declare(strict_types=1);

namespace External\HannahBundle\Admin\Actions;

use External\HannahBundle\SAP\Exception\SAPException;
use External\HannahBundle\SAP\Util\SAPApi;
use KupShop\AdminBundle\Admin\Actions\AbstractAction;
use KupShop\AdminBundle\Admin\Actions\ActionResult;
use KupShop\AdminBundle\Admin\Actions\IAction;

class SynchronizeOrderAction extends AbstractAction implements IAction
{
    /** @var SAPApi */
    private $api;

    /**
     * @required
     */
    public function setSAPApi(SAPApi $api): void
    {
        $this->api = $api;
    }

    public function getTypes(): array
    {
        return ['orders'];
    }

    public function getName(): string
    {
        return '[OC] Aktualizovat v SAPu';
    }

    public function showInMassEdit()
    {
        return true;
    }

    public function execute(&$data, array $config, string $type): ActionResult
    {
        if (!($id = $this->getId())) {
            return new ActionResult(false, 'Objednávka nebyla nalezena!');
        }

        $order = new \Order();
        if (!$order->createFromDB($id)) {
            return new ActionResult(false, 'Objednávka nebyla nalezena!');
        }

        try {
            if ($result = $this->api->updateOrder($order, true)) {
                $order->logHistory(
                    sprintf('[SAP] Objednávka byla v SAPu aktualizována; SAPID: %s', $result)
                );

                return new ActionResult(true, 'Objednávka byla v SAPu aktualizována.');
            }
        } catch (SAPException $e) {
            return new ActionResult(false, $e->getMessage());
        }

        return new ActionResult(false, 'Objednávku se nepodařilo aktualizovat.');
    }
}
