<?php

namespace App\Listeners;

use App\Events\AutoTraderIdAssignedToVehicle;
use App\Events\VehicleUpdated;
use App\Facades\Settings;
use App\Services\AutoTrader;
use Illuminate\Support\Facades\Event;
use Mtc\MercuryDataModels\Vehicle;

class AutoTraderAIContentActionsForVehicle
{
    /**
     * Create the event listener.
     */
    public function __construct(private readonly AutoTrader $service)
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(AutoTraderIdAssignedToVehicle $event): void
    {
        if ($this->shouldGenerateDescription($event->vehicle)) {
            $event->vehicle->update([
                'description' => $this->service->getDescription($event->vehicle)
            ]);
            if ($event->vehicle->wasChanged('description')) {
                Event::dispatch(new VehicleUpdated($event->vehicle));
            }
        }
    }

    private function shouldGenerateDescription(Vehicle $vehicle): bool
    {
        return Settings::get('ai-content-auto-trader-enabled')
            && Settings::get('ai-content-auto-trader-generate-description-on-vehicle-import')
            && empty(trim($vehicle->description ?? ''));
    }
}
