<?php

declare(strict_types=1);

namespace App\Listeners;

use App\Events\NewVehicleImported;
use App\Events\VehicleUpdatedFromImport;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleAutoTraderData;

class MarkVehicleAutoTraderExportPending
{
    /**
     * Columns whose change should cause the vehicle to be re-sent to AutoTrader Hub.
     *
     * `vrm_condensed` is a derived accessor on Vehicle; wasChanged() effectively
     * only triggers on the real persisted column `registration_number`. Listed
     * here intentionally so the contract is explicit and survives a future
     * promotion to a real column.
     */
    private const TRACKED_COLUMNS = [
        'registration_number',
        'vrm_condensed',
        'price',
        'image_checksum',
        'description',
        'attention_grabber',
        'odometer_mi',
        'is_new',
        'is_demo',
        'is_published',
        'is_sold',
        'first_registration_date',
        'main_video_url',
    ];

    public function handle(NewVehicleImported|VehicleUpdatedFromImport $event): void
    {
        $vehicle = $event->vehicle;

        if ($event instanceof VehicleUpdatedFromImport && !$vehicle->wasChanged(self::TRACKED_COLUMNS)) {
            return;
        }

        $this->markPending($vehicle);
    }

    private function markPending(Vehicle $vehicle): void
    {
        VehicleAutoTraderData::query()->updateOrCreate(
            ['vehicle_id' => $vehicle->id],
            ['pending_at_export' => true],
        );
    }
}
