<?php

namespace App\Classes\Modules\Orders\Processors;

use App\Classes\Modules\Addresses\Services\FetchesAddress;
use App\Classes\Modules\Orders\Standards\Rules\CanApproveChangeOrderAddress;
use App\Classes\Modules\Orders\Services\UpdatesOrdersAddress;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\Modules\Orders\Processors\UpdateDoFromVTPortalProcessor;

use Illuminate\Http\Request;

class ApproveChangeOrderAddressProcessor
{
    /** @var CanApproveChangeOrderAddress */
    private $canApproveChangeOrderAddress;

    /** @var FetchesAddress */
    private $fetchesAddress;

    /** @var UpdatesOrdersAddress */
    private $updatesOrdersAddress;

    /**
     * ApproveChangeOrderAddressProcessor constructor.
     * @param CanApproveChangeOrderAddress $canApproveChangeOrderAddress
     * @param FetchesAddress $fetchesAddress
     * @param UpdatesOrdersAddress $updatesOrdersAddress
     */
    public function __construct(CanApproveChangeOrderAddress $canApproveChangeOrderAddress, FetchesAddress $fetchesAddress, UpdatesOrdersAddress $updatesOrdersAddress, UpdateDoFromVTPortalProcessor $updateDoFromVTPortalProcessor)
    {
        $this->canApproveChangeOrderAddress = $canApproveChangeOrderAddress;
        $this->fetchesAddress = $fetchesAddress;
        $this->updatesOrdersAddress = $updatesOrdersAddress;
        $this->updateDoFromVTPortalProcessor = $updateDoFromVTPortalProcessor;
    }


    /**
     * @param Request $request
     * @return mixed
     * @throws \App\Classes\Exceptions\AccessForbiddenException
     * @throws \App\Classes\Exceptions\MalformedRequestException
     * @throws \App\Classes\Exceptions\RequestValidationException
     */
    public function execute(Request $request)
    {
        $status = (int) $request->route('status');

        $this->canApproveChangeOrderAddress->passes();

        $address = $this->fetchesAddress->execute(['id' => $request->route('id')]);

        if($status === ApprovalStatus::APPROVED){
            $address->owner->addresses()->update(['status' => ApprovalStatus::EXPIRED]);
        }

        $address = $this->updatesOrdersAddress->execute($address, $status);

        $vt_do_update = $this->updateDoFromVTPortalProcessor->execute($address);

        return $address;
    }
}
