<?php

namespace App\Jobs;

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 RemoveAutoTraderReferences implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

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

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $this->vehicle->loadMissing([
            'mediaUses.media'
        ]);

        $this->vehicle->update(['auto_trader_id' => null]);

        $this->vehicle->mediaUses->each(fn($mediaUse) =>
            optional($mediaUse->media)->update(['auto_trader_id' => null]));
    }
}
