<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use App\Models\Asset;

/**
 * Class UniqueAssetTagForSerialNo
 *
 * This rule checks if the provided asset_tag is unique for a given serial #.
 *
 * @package App\Rules
 */
class UniqueAssetTagForSerialNo implements ValidationRule
{
    /**
     * The serial # for which to check the uniqueness of asset_tag.
     *
     * @var string
     */
    protected $serialNo;

    /**
     * Create a new rule instance.
     *
     * @param string $serialNo The serial # for which to check uniqueness.
     */
    public function __construct($serialNo)
    {
        $this->serialNo = $serialNo;
    }

    /**
     * Run the validation rule.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        // Check if the asset_tag is unique for the given serialNo
        if (Asset::where('serial_no', "!=", $this->serialNo)->where('asset_tag', $value)->count() !== 0) {
            $fail('The asset tag # is already associated with another asset.');
            return;
        }
    }
}
