<?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\ShouldBeUnique;
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',
        ]);

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