<?php

namespace App\Jobs;

use App\Facades\Labels;
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\Collection;
use Mtc\MercuryDataModels\Label;
use Mtc\MercuryDataModels\Vehicle;

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

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

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        if (empty($this->label->data['auto_assign'])) {
            return;
        }

        Vehicle::query()
            ->chunk(100, fn (Collection $chunk) => $chunk->each(fn (Vehicle $vehicle) => $this->syncLabel($vehicle)));
    }

    private function syncLabel(Vehicle $vehicle): void
    {
        if (Labels::shouldAssign($vehicle, $this->label)) {
            $vehicle->labels()->attach($this->label->id);
        }
    }
}
