<?php

namespace App\Jobs;

use App\Observers\VehicleObserver;
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 Mtc\MercuryDataModels\Vehicle;

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

    public $timeout = 0;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(private readonly string $provider)
    {
        $this->onQueue('sync');
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if (tenant('type') === 'listing') {
            return;
        }
        $observer = App::make(VehicleObserver::class);

        Vehicle::query()
            ->with([
                'make',
                'model',
                'fuelType',
                'transmission',
                'bodyStyle',
            ])
            ->when(!empty($this->provider), fn($query) => $query->where('stock_provider', $this->provider))
            ->chunk(150, fn($chunk) => $chunk->each(fn(Vehicle $entry) => $this->update($entry, $observer)));
    }

    private function update(Vehicle $entry, VehicleObserver $observer): void
    {
        $observer->setSearchableContent($entry, true);
        $entry->save();
    }
}
