<?php


namespace Shop\Modules\AdminOrderItems;


use ActiveTable\Contracts\CommandInterface;
use ActiveTable\DataTableEngine;
use Diamond\Helpers\Form;
use Shop\Domain\State\Contracts\StateEntityInterface;
use Shop\UseCases\Checkout\Checkout;
use Shop\UseCases\Checkout\Exceptions\CheckoutException;
use Symfony\Component\HttpFoundation\RedirectResponse;

class ChangeStateCommand implements CommandInterface
{

    protected $tableEngine;
    protected $stateEntity;
    protected $checkoutUseCase;

    public function __construct(DataTableEngine $tableEngine, StateEntityInterface $stateEntity, Checkout $checkoutUseCase)
    {
        $this->tableEngine = $tableEngine;
        $this->stateEntity = $stateEntity;
        $this->checkoutUseCase = $checkoutUseCase;
    }

    public function process(): void
    {
        $ids = Form::getIdsFromRequest();

        $success = $error = [];

        foreach ($ids as $id) {
            try {
                $this->checkoutUseCase->changeOrderItemState($id, $this->stateEntity);
                $success [] = $id;
            } catch (CheckoutException $ex) {
                $error [] = $id;
            }
        }

        if (count($error)) {
            Form::addTableNotice(
                Form::buildErrorMessage(sprintf(
                    'При смене состояний позиций %s произошел сбой' , implode(',', $error)
                ))
            );
        }

        if (count($success)) {
            Form::addTableNotice(
                Form::buildSuccessMessage(sprintf(
                    'Позиций %s успешно изменили состояние на `%s`' , implode(',', $success), $this->stateEntity->getTitle()
                ))
            );
        }

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

}