<?php

namespace App\Jobs;

use App\Jobs\Operations\CapturePolicySnapshotWorkerJob;
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;

class CapturePolicySnapshotJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public ?OperationRun $operationRun = null;

    /**
     * @param  array<string, mixed>  $context
     */
    public function __construct(
        public int $tenantId,
        public int $userId,
        public int $policyId,
        public bool $includeAssignments = true,
        public bool $includeScopeTags = true,
        public ?string $createdBy = null,
        ?OperationRun $operationRun = null,
        public array $context = [],
    ) {
        $this->operationRun = $operationRun;
    }

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

        $this->operationRun->refresh();

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

        $runs->updateRun($this->operationRun, 'running');
        $runs->incrementSummaryCounts($this->operationRun, ['total' => 1]);

        dispatch(new CapturePolicySnapshotWorkerJob(
            tenantId: $this->tenantId,
            userId: $this->userId,
            policyId: $this->policyId,
            includeAssignments: $this->includeAssignments,
            includeScopeTags: $this->includeScopeTags,
            createdBy: $this->createdBy,
            operationRun: $this->operationRun,
            context: $this->context,
        ));
    }
}
