<?php

namespace App\Jobs;

use App\Models\Victim;
use App\Services\Integrations\NsrRegistryService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class PushNsrToRegistry implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $tries = 3;
    public $timeout = 120;
    public $backoff = [60, 300, 900];

    protected $victimId;
    protected $recordType;
    protected $triggeredBy;

    public function __construct($victimId, string $recordType = 'case', $triggeredBy = null)
    {
        $this->victimId = $victimId;
        $this->recordType = $recordType;
        $this->triggeredBy = $triggeredBy;
        $this->onQueue('integrations');
    }

    public function handle(NsrRegistryService $service): void
    {
        $victim = Victim::find($this->victimId);

        if (!$victim) {
            Log::warning('NGBVD queued NSR push skipped; victim record no longer exists.', [
                'victim_id' => $this->victimId,
                'record_type' => $this->recordType,
            ]);
            return;
        }

        $service->pushVictim($victim, $this->recordType);
    }
}
