<?php

namespace App\Listeners;

use App\Events\VehicleUpdated;
use App\Facades\Settings;
use App\Jobs\ExportVehicleToAutoTrader;
use App\Jobs\RemoveAutoTraderReferences;
use App\Modules\Stock\AutoTraderStock;
use Illuminate\Support\Facades\Bus;

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

    public function handle(VehicleUpdated $event): void
    {
        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();
        }

        $jobs = [
            new ExportVehicleToAutoTrader($vehicle),
        ];

        if (
            ((Settings::get('automotive-sales-channels-auto-trader-unpublish-sold', false) ?? false) &&
            $vehicle->wasChanged('is_sold') &&
            $vehicle->is_sold)
        ) {
            $jobs[] = new RemoveAutoTraderReferences($vehicle);
        } elseif (
            ((Settings::get('automotive-sales-channels-auto-trader-unpublish-reserved', false) ?? false) &&
                $vehicle->wasChanged('is_reserved') &&
                $vehicle->is_reserved)
        ) {
            $jobs[] = new RemoveAutoTraderReferences($vehicle);
        }

        Bus::chain($jobs)->dispatch();
    }
}
