<?php

namespace App\Jobs;

use App\Services\OpenAI;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Collection;
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 CreateAIVehicleDescriptions implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public $timeout = 0;

    /**
     * Create a new job instance.
     */
    public function __construct(private readonly bool $retry = false, private readonly ?Collection $for_vehicles = null)
    {
        $this->onQueue('sync');
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $open_ai = App::make(OpenAI::class);
        if ($this->for_vehicles) {
            $vehicles = $this->for_vehicles->filter(fn($vehicle) => empty($vehicle->description));
        } else {
            $vehicles = Vehicle::query()
                ->when(!$this->retry, fn($query) => $query->where(function ($query) {
                    $query->whereNull('description')
                        ->orWhere('description', '');
                }))
                ->get();
        }

        dump($vehicles->count() . ' to generate');
        foreach ($vehicles as $vehicle) {
            try {
                $description = $open_ai->getDescription($vehicle);
                if (!empty($description)) {
                    $vehicle->update([
                        'description' => '<p>' . $description . '</p>'
                    ]);
                }
            } catch (\Exception $exception) {
                Log::info($exception->getMessage(), $exception->getTrace());
            }
        }
    }
}
