<?php


namespace Shop\Modules\AdminOrders;


use ActiveTable\Contracts\CommandInterface;
use Diamond\Helpers\Form;
use Shop\Application\Shopping\Exceptions\ShoppingException;
use Shop\Application\Shopping\MergeCustomerOrders\MergeCountOrdersException;
use Shop\Application\Shopping\MergeCustomerOrders\MergeOrdersFoundSomeContractorsException;
use Shop\Application\Shopping\MergeCustomerOrders\MergeOrdersFoundSomeCustomerException;
use Shop\Application\Shopping\ShoppingService;
use Symfony\Component\HttpFoundation\RedirectResponse;

class MergeOrdersCommand implements CommandInterface
{
    protected $checkoutUseCase;

    public function __construct(ShoppingService $checkoutUseCase)
    {
        $this->checkoutUseCase = $checkoutUseCase;
    }

    /**
     *
     */
    public function process(): void
    {

        $ids = Form::getIdsFromRequest();

        try {
            $newOrder = $this->checkoutUseCase->mergeCustomerOrdersByIds($ids);

            Form::addTableNotice(Form::buildSuccessMessage(
                sprintf(
                    'Заказы успешно объединены c заказом %s',
                    $newOrder->getOrderCode()
                )
            ));
        } catch (MergeCountOrdersException $ex) {
            Form::addTableNotice(Form::buildErrorMessage('Для объединения заказов необходимо выбрать минимум две записи'));
        } catch (MergeOrdersFoundSomeCustomerException $ex) {
            Form::addTableNotice(Form::buildErrorMessage('Заказы должны принадлежать одному покупателю.'));
        }
        catch (MergeOrdersFoundSomeContractorsException $ex) {
            Form::addTableNotice(Form::buildErrorMessage('Заказы должны принадлежать одной торговой точке'));
        }
        catch (ShoppingException $ex) {
            Form::addTableNotice(Form::buildErrorMessage('При объединении произошла ошибка'));
        }

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

}