<?php

namespace App\Classes\Modules\ControllersLogic\Orders;

use App\Classes\Modules\Accounts\Exceptions\CannotCreateOrderException;
use App\Classes\Modules\ControllerLogic\Exceptions\InternalServerErrorException;
use App\Classes\Modules\Orders\DataTransferObjects\OrderObject;
use App\Classes\Modules\Orders\Services\CreatesOrder;
use App\Classes\Modules\Orders\Services\Steps\UpdatesOrderSteps;
use App\Classes\Modules\Orders\Services\UpdatesOrderWarehouse;
use App\Classes\ValueObjects\Constants\HttpStatus;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CreateOrderLogic
{

    /** @var CreatesOrder */
    private $createOrder;

    /** @var UpdatesOrderWarehouse */
    private $updatesOrderWarehouse;

    /** @var UpdatesOrderSteps */
    private $updateOrderSteps;

    /**
     * CreateOrderLogic constructor.
     * @param CreatesOrder $createOrder
     * @param UpdatesOrderWarehouse $updatesOrderWarehouse
     * @param UpdatesOrderSteps $updateOrderSteps
     */
    public function __construct(CreatesOrder $createOrder, UpdatesOrderWarehouse $updatesOrderWarehouse, UpdatesOrderSteps $updateOrderSteps)
    {
        $this->createOrder = $createOrder;
        $this->updatesOrderWarehouse = $updatesOrderWarehouse;
        $this->updateOrderSteps = $updateOrderSteps;
    }


    /**
     * @param int $companyId
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws InternalServerErrorException
     * @throws \App\Classes\Modules\Accounts\Exceptions\CannotUpdateOrderWarehouseException
     */
    public function execute(int $companyId, Request $request) {
        try {

            $order = new OrderObject($request->input('marking'), $companyId, 1);

            /** @var int $orderId */
            $orderId = $this->createOrder->execute($order);

            $this->updatesOrderWarehouse->execute($orderId, $request->input('warehouse_id'), 0);
            $this->updatesOrderWarehouse->execute($orderId, $request->input('warehouse_id'), 1);

            $this->updateOrderSteps->execute($orderId, $request);

            return new JsonResponse(null, HttpStatus::REQUEST_ACCEPTED);

        } catch (CannotCreateOrderException $exception){
            throw new InternalServerErrorException("Failed to create order because {$exception->getMessage()}");
        }
    }
}