<?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 readonly ApiNotification|null $apiNotification = null
    ) {
        $this->onQueue('motors-batch');
        $this->import = App::make(AutoGrabToVehicleImport::class);
    }

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

            if ($this->apiNotification) {
                $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['lead'])) {
            $this->import->update($this->input['lead']);
        } elseif ($this->input['event'] !== 'DEACTIVATE') {
            $this->import->add($this->input['lead']);
        }
    }
}
