<?php

namespace App\Jobs\Operations;

use App\Jobs\Middleware\EnsureQueuedExecutionLegitimate;
use App\Models\OperationRun;
use App\Services\OperationRunService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use RuntimeException;
use Throwable;

abstract class BulkOperationWorkerJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public ?OperationRun $operationRun = null;

    /**
     * Create a new job instance.
     *
     * @param  array<string, mixed>  $context
     */
    public function __construct(
        public int $tenantId,
        public int $userId,
        public string $itemId,
        ?OperationRun $operationRun = null,
        public array $context = [],
    ) {
        $this->operationRun = $operationRun;
    }

    /**
     * @return array<int, object>
     */
    public function middleware(): array
    {
        return [new EnsureQueuedExecutionLegitimate];
    }

    public function handle(OperationRunService $runs): void
    {
        if (! $this->operationRun instanceof OperationRun) {
            throw new RuntimeException('OperationRun is required for bulk worker jobs.');
        }

        $this->operationRun->refresh();

        if ($this->operationRun->status === 'completed') {
            return;
        }

        try {
            $this->process($runs);
        } catch (Throwable $e) {
            $runs->failRun($this->operationRun, $e);

            throw $e;
        }
    }

    abstract protected function process(OperationRunService $runs): void;
}
