<?php

declare(strict_types=1);

namespace External\ZNZBundle\Admin\Actions;

use External\ZNZBundle\Exception\ZNZException;
use External\ZNZBundle\Util\ZNZBlockUpdater;
use External\ZNZBundle\Util\ZNZUtil;
use KupShop\AdminBundle\Admin\Actions\AbstractAction;
use KupShop\AdminBundle\Admin\Actions\ActionResult;
use KupShop\AdminBundle\Admin\Actions\IAction;

/**
 * Aktualizace popisku+ smerem z e-shopu do Heliosu. Tim triggerneme vygenerovani zmeny, ktera se nasledne presene na
 * vsechny ostatni e-shopy.
 */
class UpdateDescriptionToHeliosAction extends AbstractAction implements IAction
{
    public function __construct(
        private readonly ZNZUtil $znzUtil,
        private readonly ZNZBlockUpdater $blockUpdater,
    ) {
    }

    public function getTypes(): array
    {
        return ['products', /* 'producers', */ 'templates'];
    }

    public function getName(): string
    {
        return '[ZNZ] Přenést na další weby';
    }

    public function isVisible()
    {
        if ($type = getVal('s')) {
            if ('templates' === substr($type, 0, -4)) {
                return $this->dialogData['id_category'] === $this->znzUtil->getSeriesTemplateCategoryId();
            }
        }

        return parent::isVisible();
    }

    public function showInMassEdit()
    {
        return true;
    }

    public function execute(&$data, array $config, string $type): ActionResult
    {
        $languages = $config['languages'] ?? [];
        if (empty($languages)) {
            return new ActionResult(false, 'Nebyl vybrán žádný jazyk!');
        }

        try {
            $result = $this->blockUpdater->update(
                $type,
                (int) $this->getId(),
                $languages
            );
        } catch (ZNZException $e) {
            return new ActionResult(false, "Aktualizace se nezdařila: {$e->getMessage()}");
        }

        return new ActionResult($result);
    }
}
