<?php

namespace App\Classes\Modules\Orders\Services\Steps;

use App\Classes\Modules\Orders\DataTransferObjects\StepObject;
use App\Classes\ValueObjects\Constants\OrderSteps;
use App\Models\Order;
use App\Models\OrderStep;

class UpdatesOrderCurrentStep
{

    public function execute(int $orderId, StepObject $step){

        $orderStep = OrderStep::where('order_id', $orderId)
            ->where('complete', 0)->orderBy('sequence')->first();

        $nextStep = $orderStep ? $orderStep->reference_id : null;

        $repository = order::findOrFail($orderId);
        $repository->current_step = $nextStep;

        if($nextStep === null && $step !== OrderSteps::ORDER_PROCESSING_STEP){
            $repository->complete = true;
        }

        $repository->save();
    }
}