<?php

namespace App\Jobs;

use App\Services\OpenAI;
use Exception;
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\Vehicle;

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

    public function __construct(
        protected readonly Vehicle $vehicle,
    ) {
        $this->onQueue('sync');
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(): void
    {
        if (empty($this->vehicle) || !empty($this->vehicle->description)) {
            return;
        }

        $openAI = App::make(OpenAI::class);
        try {
            $description = $openAI->getDescription($this->vehicle);
            if (!empty($description)) {
                $this->vehicle->update([
                    'description' => '<p>' . $description . '</p>'
                ]);
            }
        } catch (Exception $exception) {
            Log::debug("Open AI: " . $this->vehicle->id . " - " . $exception->getMessage());
        }
    }
}
