<?php

namespace App\Jobs;

use App\Facades\Settings;
use App\SalesChannelType;
use App\Services\AutoTraderHub;
use App\Traits\UsesSalesChannelRules;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Mtc\MercuryDataModels\Vehicle;

class ExportVehicleToAutoTrader implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;
    use UsesSalesChannelRules;

    /**
     * Create a new job instance.
     */
    public function __construct(private readonly Vehicle $vehicle)
    {
        //
    }

    /**
     * Execute the job.
     */
    public function handle(AutoTraderHub $service): void
    {
        $this->vehicle->loadMissing([
            'make',
            'model',
            'transmission',
            'fuelType',
            'bodyStyle',
            'features',
            'equipment',
            'mediaUses.media',
            'dealership',
            'attributeValues',
        ]);

        if ($this->hasSalesChannelRules(SalesChannelType::AUTOTRADER)) {
            $rules = $this->getSalesChannelRules(SalesChannelType::AUTOTRADER);
            if (!$this->applyModelConditions($this->vehicle, $rules)) {
                $this->removeFromAutoTraderIfExported($service);
                return;
            }
        }
        $service->setToken(Settings::get('auto-trader-hub-token'))
            ->export($this->vehicle);
    }

    /**
     * When a vehicle no longer matches the AutoTrader sales-channel rules (e.g. its VRM was
     * changed to an excluded value such as a new-plate "111") but was previously exported,
     * pull it from AutoTrader and clear the local references instead of silently leaving a
     * stale listing behind.
     */
    private function removeFromAutoTraderIfExported(AutoTraderHub $service): void
    {
        if (!Settings::get('auto-trader-hub-remove-unmatched-vehicles')) {
            return;
        }

        if (empty($this->vehicle->auto_trader_id)) {
            return;
        }

        $service->setToken(Settings::get('auto-trader-hub-token'))
            ->removeVehicle($this->vehicle);

        RemoveAutoTraderReferences::dispatch($this->vehicle);
    }
}
