<?php

namespace App\Jobs;

use App\Facades\Settings;
use App\Services\AutoTraderHub;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleAutoTraderDerivativeMapping;

class ApplyAutoTraderDerivativeMapping implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public function __construct(private readonly int $vehicleId)
    {
    }

    public function handle(): void
    {
        $vehicle = Vehicle::query()
            ->with([
                'dealership', 'make', 'model', 'fuelType', 'drivetrain',
                'transmission', 'bodyStyle', 'mediaUses.media', 'features',
                'equipment', 'specs', 'autoTraderData',
            ])
            ->find($this->vehicleId);

        if (!$vehicle) {
            return;
        }

        if ($vehicle->autoTraderData?->derivative_id) {
            return;
        }

        $mapping = VehicleAutoTraderDerivativeMapping::query()
            ->where('make_id', $vehicle->make_id)
            ->where('model_id', $vehicle->model_id)
            ->where('derivative', $vehicle->derivative ?? '')
            ->first();

        if (!$mapping) {
            return;
        }

        $vehicle->autoTraderData()->updateOrCreate(
            ['vehicle_id' => $vehicle->id],
            [
                'derivative_id' => $mapping->at_derivative_id,
                'at_export_error' => null,
            ],
        );

        $vehicle->load('autoTraderData');

        if (Settings::get('sales-channels-auto-trader-method') === 'ftp') {
            return;
        }

        $token = Settings::get('auto-trader-hub-token');
        if (!$token) {
            return;
        }

        try {
            App::make(AutoTraderHub::class)->setToken($token)->export($vehicle);
        } catch (\Exception $e) {
            Log::warning('Failed to re-export vehicle after applying derivative mapping', [
                'vehicle_id' => $vehicle->id,
                'error' => $e->getMessage(),
            ]);
        }
    }
}
