<?php

namespace App\Classes\Modules\ControllersLogic\Orders;

use App\Classes\Modules\ControllerLogic\Exceptions\InternalServerErrorException;
use App\Classes\Modules\Orders\DataTransferObjects\StepObject;
use App\Classes\Modules\Orders\DataTransferObjects\TrackingNumberObject;
use App\Classes\Modules\Orders\Services\Attachments\UpdatesTrackingNumber;
use App\Classes\Modules\Orders\Services\UpdatesOrderWarehouse;
use App\Classes\Modules\Orders\Services\Steps\UpdatesStepCompleteDate;
use App\Classes\ValueObjects\Constants\HttpStatus;
use App\Classes\ValueObjects\Constants\OrderSteps;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class UpdateReceiveNoteLogic
{
    /** @var  UpdatesOrderWarehouse */
    private $setsOrderWarehouse;

    /** @var  UpdatesStepCompleteDate */
    private $updatesStepCompleteDate;

    /** @var UpdatesTrackingNumber */
    private $updatesTrackingNumber;

    /**
     * UpdateReceiveNoteLogic constructor.
     * @param UpdatesOrderWarehouse $setsOrderWarehouse
     * @param UpdatesStepCompleteDate $updatesStepCompleteDate
     * @param UpdatesTrackingNumber $updatesTrackingNumber
     */
    public function __construct(UpdatesOrderWarehouse $setsOrderWarehouse, UpdatesStepCompleteDate $updatesStepCompleteDate, UpdatesTrackingNumber $updatesTrackingNumber)
    {
        $this->setsOrderWarehouse = $setsOrderWarehouse;
        $this->updatesStepCompleteDate = $updatesStepCompleteDate;
        $this->updatesTrackingNumber = $updatesTrackingNumber;
    }


    /**
     * @param string $orderId
     * @param Request $request
     * @return JsonResponse
     * @throws InternalServerErrorException
     */
    public function execute(string $orderId, Request $request){

        try{

            $stepObject = new StepObject(OrderSteps::ORDER_WAREHOUSE_RECEIVING_STEP, $request->input('complete_date'));

            $this->setsOrderWarehouse->execute($orderId,  $request->input('warehouse_id'), 0);
            $this->setsOrderWarehouse->execute($orderId,  $request->input('warehouse_id'), 2);
            $this->updatesStepCompleteDate->execute($orderId, $stepObject);

            $trackingNumberObject = new TrackingNumberObject(0, $request->input('tracking_number'));
            $this->updatesTrackingNumber->execute($orderId, $trackingNumberObject);

            return new JsonResponse([], HttpStatus::RESOURCE_CREATED);

        }catch(\Exception $exception) {
            throw new InternalServerErrorException("Failed to update order's receive note because {$exception->getMessage()}");
        }
    }

}