<?php


namespace Shop\Application\Shopping\CreateCustomerOrder;


use Shop\Application\Office\OfficeService;
use Shop\Presentation\Config\Main;
use Shop\Infrastructure\Repositories\CustomerOrder\CustomerOrderRepository;

class CreateCustomerOrderHandler
{
    protected $mainConf;
    protected $customerOrderRepository;
    protected $officeService;

    use BuildOrderPositionTrait;

    /**
     * CreateCustomerOrderHandler constructor.
     * @param Main $mainConf
     * @param CustomerOrderRepository $customerOrderRepository
     * @param OfficeService $officeService
     */
    public function __construct(Main $mainConf, CustomerOrderRepository $customerOrderRepository,
                                OfficeService $officeService)
    {
        $this->mainConf = $mainConf;
        $this->customerOrderRepository = $customerOrderRepository;
        $this->officeService = $officeService;
    }

    /**
     * @param CreateCustomerOrderCommand $command
     */
    public function handle(CreateCustomerOrderCommand $command): void
    {
        $orderRequest = $command->getOrderRequest();

        $customer = $this->officeService->getCustomerById($orderRequest->getClientId());

        if(!$conteractorId = $customer->getManager()->getShop()->getContractorId()){
            throw new CreateCustomerOrderException('contractor not set');
        }

        $order = CustomerOrderRepository::createEntity()
            ->setCustomerId($customer->getId())
            ->setContractorId($conteractorId)
            //------------
            ->setPaymentId($orderRequest->getPaymentId())
            ->setComment($orderRequest->getComment())
            ->setDeliveryAddress($orderRequest->getDeliveryAddress())
            ->setStateId($this->mainConf->getStateDefault())
            ->setDiscountSumm($orderRequest->getDiscount());

        foreach ($orderRequest->getItems() as $item) {
            $orderItem = $this->buildOrderItem($item);
            $orderItem->setStateId($this->mainConf->getStateDefault());
            $order->addOrderItem($orderItem);
        }

        $this->customerOrderRepository->save($order);

        $command->getOrderResult()->setOrder($order);
    }
}