<?php

namespace App\Jobs;

use App\Imports\CapVehicleImport;
use App\Master\Models\CapVehicle;
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;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Throwable;

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

    public int $timeout = 3600;

    public function __construct(
        protected readonly string $filePath,
        protected readonly string $type,
        protected readonly bool $clearExisting = false,
        protected readonly string $disk = 'local'
    ) {
        $this->onQueue('sync');
    }

    public function handle(): void
    {
        if ($this->clearExisting) {
            CapVehicle::query()
                ->where('type', $this->type)
                ->delete();
        }

        $import = new CapVehicleImport($this->type);
        $fullPath = Storage::disk($this->disk)->path($this->filePath);

        Excel::import($import, $fullPath);

        if (Storage::disk($this->disk)->exists($this->filePath)) {
            Storage::disk($this->disk)->delete($this->filePath);
        }
    }

    public function failed(?Throwable $exception): void
    {
        Log::error('CAP vehicles import failed', [
            'type' => $this->type,
            'file' => $this->filePath,
            'error' => $exception?->getMessage(),
        ]);
    }
}
