<?php

/**
 * Copyright © 2016 Filoblu S.r.l. All rights reserved.
 */

namespace FiloBlu\Esb\Model\Rest;

use Exception;
use FiloBlu\Esb\Api\Data\AcknowledgeInterface;
use FiloBlu\Esb\Api\Data\AcknowledgeInterfaceFactory;
use FiloBlu\Esb\Api\ExternalOrderInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order;

/**
 * REST Api to save external orders
 */
class ExternalOrder implements ExternalOrderInterface
{
    /**
     * @var SearchCriteriaBuilder
     */
    protected $searchCriteriaBuilder;
    /**
     * @var OrderRepositoryInterface
     */
    protected $orderRepository;
    /**
     * @var AcknowledgeInterfaceFactory
     */
    protected $acknowledgeFactory;

    public function __construct(
        SearchCriteriaBuilder       $searchCriteriaBuilder,
        OrderRepositoryInterface    $orderRepositoryInterface,
        AcknowledgeInterfaceFactory $acknowledgeFactory
    )
    {
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->orderRepository = $orderRepositoryInterface;
        $this->acknowledgeFactory = $acknowledgeFactory;
    }

    /**
     * @param OrderInterface $orderData
     * @return AcknowledgeInterface
     * @throws Exception
     * @description This API is used only to update the FilobluExtensionAttributes of an order
     */
    public function updateFilobluExtensionAttributes(OrderInterface $orderData)
    {

        $searchCriteria = $this->searchCriteriaBuilder->addFilter(OrderInterface::INCREMENT_ID, $orderData->getIncrementId())->create();
        $result = $this->orderRepository->getList($searchCriteria);

        if ($result->getTotalCount() === 0) {
            throw new NoSuchEntityException(__("No such order with increment id = %id", ['id' => $orderData->getIncrementId()]));
        }

        $items = $result->getItems();

        /** @var OrderInterface|Order $order */
        $order = reset($items);
        $orderData->setEntityId($order->getId());

        $this->orderRepository->save($orderData);

        return $this->acknowledgeFactory->create(
            [
                'data' =>
                    [
                        'status' => 'success',
                        'code' => 'order' . '_' . $order->getIncrementId(),
                        'message' => __('Order %1 filobluExtensionAttributes data has been updated', $order->getIncrementId()),
                        'description' => __('Magento Order: %1 filobluExtensionAttributes data updated', $order->getIncrementId()),
                        'flow' => 'update_order',
                        'order_increment_id' => $order->getIncrementId()
                    ]
            ]
        );
    }

}
