<?php

namespace App\Classes\Modules\Orders\Services;


use App\Classes\Modules\Accounts\Exceptions\CannotCreateOrderException;
use App\Classes\Modules\Orders\DataTransferObjects\OrderObject;
use App\Classes\ValueObjects\Constants\HttpStatus;
use App\Classes\ValueObjects\Constants\OrderSteps;
use App\Models\Company;
use App\Models\Order;
use Illuminate\Http\JsonResponse;

class CreatesOrder
{

    /** @var Order */
    private $repository;

    /**
     * CreatesOrder constructor.
     * @param Order $repository
     */
    public function __construct(Order $repository)
    {
        $this->repository = $repository;
    }

    /**
     * @param OrderObject $order
     * @return JsonResponse
     * @throws CannotCreateOrderException
     */
    public function execute(OrderObject $order) {

        try {
            $address = Company::findOrFail($order->getCompanyId())->addressBook()->where('default', true)->first();
//            $address = AddressBook::where('company_id', $order->getCompanyId())
//                ->where('default', true)->first();

            if(!$address){
                return new JsonResponse(['message' => 'Failed to create order because import\'s delivery address wasn\'t found'], HttpStatus::RESOURCE_NOT_FOUND);
            }

            $this->repository->company_id = $order->getCompanyId();
            $this->repository->marking = $order->getMarking();
            $this->repository->forwarder_id = $order->getForwarderId();
            $this->repository->address_id = $address->id;
            $this->repository->current_step = OrderSteps::ORDER_PROCESSING_STEP;

            $this->repository->save();

            return $this->repository->id;

        } catch (\Exception $exception){
            throw new CannotCreateOrderException($exception->getMessage());
        }

    }

}