<?php

namespace App\Jobs;

use App\Facades\Settings;
use App\Services\AutoTraderHub;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Collection;
use Mtc\MercuryDataModels\Dealership;
use Mtc\MercuryDataModels\Vehicle;

/**
 * Detach the AutoTrader stock references for every vehicle at an AutoTrader
 * location so they can be exported as brand-new AutoTrader records. Notifies
 * AutoTrader Hub first (so it drops its stored stock ids), then clears the
 * local references and AutoTrader data per vehicle.
 */
class DetachAutoTraderReferences implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public function __construct(private readonly string $locationId)
    {
        //
    }

    public static function linkedVehicleQuery(string $locationId): Builder
    {
        $dealershipIds = Dealership::all()
            ->filter(fn (Dealership $dealership) =>
                (string) ($dealership->data['auto-trader-location-id'] ?? '') === $locationId)
            ->pluck('id');

        return Vehicle::query()
            ->withTrashed()
            ->whereIn('dealership_id', $dealershipIds)
            ->whereNotNull('auto_trader_id');
    }

    public function handle(): void
    {
        $vehicleIds = self::linkedVehicleQuery($this->locationId)->pluck('id');

        if ($vehicleIds->isEmpty()) {
            return;
        }

        $this->notifyHub($vehicleIds);

        Vehicle::query()
            ->withTrashed()
            ->whereIn('id', $vehicleIds)
            ->each(fn (Vehicle $vehicle) => RemoveAutoTraderReferences::dispatch($vehicle));
    }

    private function notifyHub(Collection $vehicleIds): void
    {
        if (Settings::get('sales-channels-auto-trader-method') === 'ftp') {
            return;
        }

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

        $notified = resolve(AutoTraderHub::class)
            ->setToken($token)
            ->clearReferences($vehicleIds);

        // Fail before clearing anything locally so a retry re-runs the full
        // detach with the same set of vehicles.
        if (!$notified) {
            throw new \RuntimeException('AutoTrader Hub rejected the clear-references request');
        }
    }
}
