<?php


namespace Shop\Application\Shopping\ChangeOrderState;


use Shop\Config\Main;
use Shop\Domain\CustomerOrder\Contracts\CustomerOrderEntityInterface;
use Shop\Models\StateLog\StateLog;
use Shop\Repositories\CustomerOrder\CustomerOrderRepository;
use Shop\Repositories\ProviderOrder\ProviderOrderRepository;
use Shop\Repositories\StateLog\StateLogRepository;

class ChangeOrderStateHandler
{
    protected $customerOrderRepository;
    protected $providerOrderRepository;
    protected $stateLogRepository;
    protected $mainConfig;

    /**
     * ChangeOrderStateHandler constructor.
     * @param CustomerOrderRepository $customerOrderRepository
     * @param ProviderOrderRepository $providerOrderRepository
     * @param StateLogRepository $stateLogRepository
     * @param Main $mainConfig
     */
    public function __construct(CustomerOrderRepository $customerOrderRepository,
                                ProviderOrderRepository $providerOrderRepository,
                                StateLogRepository $stateLogRepository,
                                Main $mainConfig)
    {
        $this->customerOrderRepository = $customerOrderRepository;
        $this->providerOrderRepository = $providerOrderRepository;
        $this->stateLogRepository = $stateLogRepository;
        $this->mainConfig = $mainConfig;
    }

    /**
     * @param ChangeOrderStateCommand $command
     */
    public function handle(ChangeOrderStateCommand $command): void
    {
        $order = $command->getOrder();
        //add log
        $oldStateId = $order->getStateId();

        $order->setStateId($command->getStateId());

        if (is_a($order, CustomerOrderEntityInterface::class)) {
            $this->customerOrderRepository->save($order);
        } else {
            $this->providerOrderRepository->save($order);
        }

        $stateLog = new StateLog;
        $stateLog
            ->setOldStateId($oldStateId)
            ->setNewStateId($command->getStateId())
            ->setObjectId($order->getId())
            ->setTypeId(StateLog::TYPE_ORDER);

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