<?php

namespace App\Jobs;

use App\AIContentRepository;
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;
        }

        $AIContentRepository = App::make(AIContentRepository::class);
        if (!$AIContentRepository->hasEnabledIntegration()) {
            return;
        }

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