<?php

namespace App\Listeners;

use App\Events\VehicleUpdated;
use App\Facades\Settings;
use App\Jobs\ExportVehicleToAutoTrader;
use App\Modules\Stock\AutoTraderStock;
use App\Services\AutoTraderHub;
use Illuminate\Queue\InteractsWithQueue;

class SendVehicleToAutoTrader
{
    public function __construct(private AutoTraderStock $provider)
    {
        //
    }

    public function handle(VehicleUpdated $event)
    {
        if (!Settings::get('sales-channels-auto-trader-enabled') || !Settings::get('auto-trader-hub-token')) {
            return;
        }

        $vehicle = $event->getVehicle();
        if ($vehicle->wasChanged('is_published')) {
            $vehicle->data = array_merge($vehicle->data, $this->provider->setAdvertFields($vehicle->is_published));
            $vehicle->save();
        }

        ExportVehicleToAutoTrader::dispatch($vehicle);
    }
}
