<?php


namespace Shop\Application\Shopping\ChangeOrderItemState;


use Shop\Application\Shopping\Exceptions\OrderItemNotFoundException;
use Shop\Models\OrderItem\OrderItem;
use Shop\Models\StateLog\StateLog;
use Shop\Repositories\OrderItem\OrderItemRepository;
use Shop\Repositories\StateLog\StateLogRepository;

class ChangeOrderItemStateHandler
{
    protected $itemRepository;
    protected $stateLogRepository;

    /**
     * ChangeOrderItemStateHandler constructor.
     * @param OrderItemRepository $itemRepository
     * @param StateLogRepository $stateLogRepository
     */
    public function __construct(OrderItemRepository $itemRepository,
                                StateLogRepository $stateLogRepository)
    {
        $this->itemRepository = $itemRepository;
        $this->stateLogRepository = $stateLogRepository;
    }

    /**
     * @param ChangeOrderItemStateCommand $command
     * @throws \Propel\Runtime\Exception\PropelException
     */
    public function handle(ChangeOrderItemStateCommand $command): void {

        $itemId = $command->getItemId();
        $stateId  = $command->getStateId();

        /**
         * @var OrderItem $item
         */
        if (!$item = $this->itemRepository->findById($itemId)) {
            throw new OrderItemNotFoundException(sprintf('OrderItem `%s` not found', $itemId));
        }

        //state
        $stateLog = new StateLog();
        $stateLog->setOldStateId($item->getStateId());
        $stateLog->setNewStateId($stateId);
        $stateLog->setTypeId(StateLog::TYPE_ORDER_ITEM);
        $stateLog->setObjectId($item->getId());

        //item
        $item->setStateId($stateId);

        $this->itemRepository->save($item);
        $this->stateLogRepository->save($stateLog);
    }
}