<?php

namespace App\Classes\Modules\Steps\Processors;

use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Orders\DataTransferObjects\OrderObject;
use App\Classes\Modules\Steps\Services\UpdatesSteps;
use App\Classes\Modules\Steps\Standards\Rules\CanUpdateStep;
use App\Classes\ValueObjects\Constants\OrderStatus;
use App\Classes\ValueObjects\Constants\Steps;
use App\Classes\ValueObjects\Constants\OrderType;
use App\Http\Resources\StepResource;
use App\Classes\Modules\Steps\DataTransferObjects\StepsObject;
use App\Classes\Modules\Steps\Services\FetchesSteps;
use App\Classes\Modules\Unity\Processors\UpdateObligationsProcessor;
use App\Classes\Modules\Orders\Processors\UpdatesOrderCurrentStepProcessor;


use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class CompletesStepProcessor
{

    private $fetchesStep;

    private $unityUpdateObligation;

    private $updateStepProcessors;

    private $updatesOrderCurrentStep;

    public function __construct(FetchesSteps $fetchesStep, UpdateObligationsProcessor $unityUpdateObligation, CanUpdateStep $canUpdateStep, UpdatesSteps $updatesStep, UpdatesOrderCurrentStepProcessor $updatesOrderCurrentStep)
    {
        $this->fetchesStep = $fetchesStep;
        $this->unityUpdateObligation = $unityUpdateObligation;
        $this->canUpdateStep = $canUpdateStep;
        $this->updatesStep = $updatesStep;
        $this->updatesOrderCurrentStep = $updatesOrderCurrentStep;
    }

    public function execute(Request $request) {

        $orderStep = $this->fetchesStep->getRepository()->where('id', $request->get('id'))->first();

        $contractEntity = $orderStep->orderRole()->where('order_id',$orderStep->owner_id)->first();

        $obligation_hash_id = $orderStep->unity_hash_id;
        $contract_entity_signature = $contractEntity->role_signature;

        $completed = $this->unityUpdateObligation->execute($contract_entity_signature, $obligation_hash_id);

        //Unity Contract Obligation Completed Status = 3
        if(isset($completed->status) && $completed->status == OrderStatus::COMPLETE){
            $orderStepObject = new StepsObject(
                $contractEntity->company_module_id,
                $orderStep->reference,
                true,
                $orderStep->sequence,
                OrderStatus::COMPLETE,
                OrderStatus::COMPLETE,
                $completed->completed_at??date('Y-m-d H:i:s'),
                $orderStep->id,
                $orderStep->hash_id
            );

            $this->canUpdateStep->passes($orderStepObject);

            $updatedStep = $this->updatesStep->execute($orderStep, $orderStepObject);

            $this->updatesOrderCurrentStep->execute( $orderStep->order->id, $orderStep->reference);
        }

       return $orderStep;

    }
}
