<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Mtc\MercuryDataModels\Vehicle;

class UniqueVehicleRegistrationNumber implements ValidationRule
{
    public function __construct(private readonly ?int $vehicle_id = null)
    {
    }

    /**
     * Run the validation rule.
     *
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (empty($value)) {
            return;
        }
        $exists = Vehicle::query()
            ->where(fn($query) => $query->where('registration_number', $value)
                ->orWhere('vrm_condensed', str_replace([' ', '-'], '', $value)))
            ->when($this->vehicle_id, fn($query) => $query->where('id', '!=', $this->vehicle_id))
            ->exists();

        if ($exists) {
            $fail('Vehicle with this registration number already exists');
        }
    }
}
