<?php


namespace Shop\Presentation\Modules\AdminProviderOrders;


use ActiveTable\Contracts\CommandInterface;
use Diamond\Helpers\Form;
use Shop\Presentation\Config\Main;
use Shop\Domain\State\Contracts\StateEntityInterface;
use Shop\Infrastructure\Models\Order\Order;
use Shop\Infrastructure\Repositories\State\StateRepository;
use Shop\Presentation\UseCases\Checkout\Checkout;
use Shop\Presentation\UseCases\Checkout\Exceptions\CheckoutException;
use Shop\Presentation\UseCases\Checkout\Exceptions\SendProviderOrdersException;
use Symfony\Component\HttpFoundation\RedirectResponse;

class SendProviderOrderCommand implements CommandInterface
{
    protected $checkoutUseCase;
    protected $mainConf;
    protected $stateRepository;

    public function __construct(Checkout $checkoutUseCase, Main $mainConf, StateRepository $stateRepository)
    {
        $this->checkoutUseCase = $checkoutUseCase;
        $this->mainConf = $mainConf;
        $this->stateRepository = $stateRepository;
    }

    /**
     * @throws \Propel\Runtime\Exception\PropelException
     * @throws \Repo\Concrete\Exceptions\Collection
     * @throws \Throwable
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     */
    public function process(): void
    {
        //получаем id заказов
        $ids = Form::getIdsFromRequest();

        //вызываем метод отправки заказов на email
        try {
            if (!$state = $this->stateRepository->findById($this->mainConf->getStateProviderSend())) {
                Form::addTableNotice(Form::buildErrorMessage('Состояние для успешно отправленых заказов поставщика не настроено'));
                throw new CheckoutException(sprintf(
                    'default `%s` state not found', $this->mainConf->getStateProviderDefault()
                ));
            }

            $orders = $this->checkoutUseCase->sendProviderOrdersByIds($ids);

        } catch (SendProviderOrdersException $exception) {
            Form::addTableNotice(Form::buildErrorMessage('Некоторые заказы не были отправлены.'));
            $orders = $exception->getSuccess();
        } catch (CheckoutException $exception) {
            Form::addTableNotice(Form::buildErrorMessage('Отправку заказов поставщикам не удалось произвести'));
        }
        /**
         * @var Order $order
         * @var StateEntityInterface $state
         */
        if (isset($orders)) {
            foreach ($orders as $order) {
                $links [] = $order->getOrderCode();

                foreach ($order->getOrderItems() as $item) {
                    $this->checkoutUseCase->changeOrderItemState($item->getId(),$state);
                }

            }
            Form::addTableNotice(Form::buildSuccessMessage(
                sprintf('Отправка заказов %s успешно произведена.', implode(', ', $links))
            ));
        }


        RedirectResponse::create(adaptive_url([], ['fn', 'id']))->send();
    }

}