<?php

namespace App\Classes\Modules\Jobs\Processors;

use App\Classes\Exceptions\JobResourceNotFoundException;
use App\Classes\Modules\Jobs\Services\FetchesJobResult;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class FetchesJobResultProcessor
{
    /** @var FetchesJobResult */
    private $fetchesJobResult;


    /**
     * FetchesJobResultProcessor constructor.
     * @param FetchesJobResult $fetchesJobResult
     */
    public function __construct(FetchesJobResult $fetchesJobResult)
    {
        $this->fetchesJobResult = $fetchesJobResult;
    }


    /**
     * @param Request $request
     * @return Model
     * @throws \App\Classes\Exceptions\MalformedRequestException
     * @throws \App\Classes\Exceptions\JobResourceNotFoundException
     * @throws \App\Classes\Exceptions\ResourceNotFoundException
     */
    public function execute(Request $request){

        $res1 = $this->fetchesJobResult->execute(['job_id' => $request->route('job_id')]);
        if($request->route('is_last')){
            $res2 = $this->fetchesJobResult->execute(['request_signature' => $res1->request_signature, 'result_not_null' => true, 'order_by_id_desc' => true]);
            return $res2;
        }

        if(!$res1->result){
            throw new JobResourceNotFoundException('Unable to find any job based on the criteria provided');
        }

        return $res1;
    }
}
