<?php

namespace App\Jobs;

use App\Imports\PreClaimBatchRowsImport;
use App\Models\ImportBatch;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Maatwebsite\Excel\Facades\Excel;

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

    public int $importBatchId;

    public function __construct(int $importBatchId)
    {
        $this->importBatchId = $importBatchId;
    }

    public function handle(): void
    {
        $batch = ImportBatch::query()->findOrFail($this->importBatchId);

        // Ensure "completed" is only set after successful full processing.
        $batch->forceFill(['completed' => 0])->save();

        Excel::import(
            new PreClaimBatchRowsImport($batch->id),
            storage_path('app/' . $batch->file_path)
        );

        $batch->forceFill(['completed' => 1])->save();
    }

    public function failed(\Throwable $e): void
    {
        ImportBatch::query()
            ->whereKey($this->importBatchId)
            ->update(['completed' => 0]);
    }
}

