<?php

namespace App\Jobs;

use App\Contracts\AIContentDriver;
use App\Events\VehicleUpdated;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Broadcasting\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Event;
use Mtc\MercuryDataModels\Vehicle;

class CreateSingleVehicleAIDescription implements ShouldQueue, ShouldBeUnique
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    /**
     * Create a new job instance.
     */
    public function __construct(private readonly Vehicle $vehicle, private readonly AIContentDriver $service)
    {
        $this->onQueue('sync');
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $this->vehicle->update([
            'description' => $this->service->getDescription($this->vehicle)
        ]);

        if ($this->vehicle->wasChanged('description')) {
            Event::dispatch(new VehicleUpdated($this->vehicle));
        }
    }

    /**
     * We do not want multiple events happening concurrently due to rate limiting,
     * so we allow only one job per site at the same time.
     * e.g. AutoTrader CoDriver has a limit of 5req/s
     *
     * @return string
     */
    public function uniqueId(): string
    {
        return 'ai-description-generation:' . tenant('id');
    }
}
