<?php

declare(strict_types=1);

namespace App\Jobs\Middleware;

use App\Models\OperationRun;
use App\Services\OperationRunService;
use App\Services\Operations\QueuedExecutionLegitimacyGate;
use Closure;

class EnsureQueuedExecutionLegitimate
{
    /**
     * @param  mixed  $job
     * @param  callable  $next
     * @return mixed
     */
    public function handle($job, Closure $next)
    {
        $run = $this->resolveRun($job);

        if (! $run instanceof OperationRun) {
            return $next($job);
        }

        $decision = app(QueuedExecutionLegitimacyGate::class)->evaluate($run);

        if (! $decision->allowed) {
            app(OperationRunService::class)->finalizeExecutionLegitimacyBlockedRun($run, $decision);

            return null;
        }

        return $next($job);
    }

    /**
     * @param  mixed  $job
     */
    private function resolveRun($job): ?OperationRun
    {
        if (method_exists($job, 'getOperationRun')) {
            $run = $job->getOperationRun();

            return $run instanceof OperationRun ? $run : null;
        }

        if (property_exists($job, 'operationRun')) {
            $run = $job->operationRun;

            return $run instanceof OperationRun ? $run : null;
        }

        return null;
    }
}
