<?php

declare(strict_types=1);

namespace App\Jobs\Concerns;

use App\Models\OperationRun;
use App\Services\OperationRunService;
use Throwable;

trait BridgesFailedOperationRun
{
    public function failed(Throwable $exception): void
    {
        $operationRun = $this->failedBridgeOperationRun();

        if (! $operationRun instanceof OperationRun) {
            return;
        }

        app(OperationRunService::class)->bridgeFailedJobFailure($operationRun, $exception);
    }

    protected function failedBridgeOperationRun(): ?OperationRun
    {
        if (property_exists($this, 'operationRun') && $this->operationRun instanceof OperationRun) {
            return $this->operationRun;
        }

        if (property_exists($this, 'run') && $this->run instanceof OperationRun) {
            return $this->run;
        }

        $candidateIds = [];

        foreach (['operationRunId', 'bulkRunId', 'runId'] as $property) {
            if (! property_exists($this, $property)) {
                continue;
            }

            $value = $this->{$property};

            if (is_numeric($value) && (int) $value > 0) {
                $candidateIds[] = (int) $value;
            }
        }

        foreach (array_values(array_unique($candidateIds)) as $candidateId) {
            $operationRun = OperationRun::query()->find($candidateId);

            if ($operationRun instanceof OperationRun) {
                return $operationRun;
            }
        }

        return null;
    }
}
