<?php

declare(strict_types=1);

namespace KupShop\PreordersBundle\Admin\Actions;

use KupShop\AdminBundle\Admin\Actions\ActionResult;
use KupShop\PreordersBundle\Service\DynamicContexts;
use KupShop\PreordersBundle\Service\PreorderItemsUpdater;

class RecalculatePreorderPiecesAction extends UserPreorderAction
{
    public function __construct(
        private readonly PreorderItemsUpdater $itemsUpdater,
        private readonly DynamicContexts $contexts,
    ) {
    }

    public function execute(&$data, array $config, string $type): ActionResult
    {
        try {
            $userPreorder = $this->getUserPreorder();

            $this->contexts->activateUserPreorder($userPreorder);
            $this->itemsUpdater->recalculatePiecePrices($userPreorder);
        } catch (\Throwable $e) {
            return new ActionResult(false, $e->getMessage());
        }

        return new ActionResult(true);
    }

    protected function checkEnabled(): bool
    {
        return true;
    }
}
