<?php

namespace App\Jobs;

use App\Imports\AutoGrabToVehicleImport;
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\App;
use Illuminate\Support\Facades\Log;
use Mtc\MercuryDataModels\ApiNotification;

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

    protected AutoGrabToVehicleImport $import;

    /**
     * Create a new job instance.
     */
    public function __construct(
        private readonly array $input,
        private ApiNotification $apiNotification
    ) {
        $this->onQueue('motors-batch');
        $this->import = App::make(AutoGrabToVehicleImport::class);
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        try {
            $this->processVehicleData();

            $this->apiNotification->processed = 1;
            $this->apiNotification->save();
        } catch (\Exception $exception) {
            Log::error('AutoGrab notification processing failed', [
                'error' => $exception->getMessage(),
                'input' => $this->input,
                'tenant' => tenant('id'),
            ]);
            throw $exception;
        }
    }

    private function processVehicleData(): void
    {
        if ($this->import->exists($this->input)) {
            $this->import->update($this->input);
        } else {
            $this->import->add($this->input);
        }
    }
}
