<?php

namespace App\Rules;

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

class ValidateTechSpecsMakeModelMatch implements ValidationRule
{
    /**
     * Create a new rule instance.
     *
     * @param int|null $makeAndModelId
     * @param int|null $assetId
     * @param int|null $count
     */
    public function __construct(protected $makeAndModelId = null, protected $assetId = null, protected $count = null) {}

    /**
     * Run the validation rule.
     *
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (!$value) {
            return; // Allow null values as it's nullable
        }

        $makeAndModelId = $this->makeAndModelId;

        // If make_and_model_id is not provided, fallback to asset's make_and_model_id
        if (!$makeAndModelId) {
            $asset = Asset::select('make_and_model_id')->find($this->assetId);

            if ($asset === null) {
                return;
            }

            $makeAndModelId = $asset->make_and_model_id;
        }

        // Check if the make_and_model belongs to the asset type
        if (TechnicalSpecs::select('id')->where('id', $value)->where('make_and_model_id', $makeAndModelId)->exists() === false) {
            $lineInfo = $this->count ? 'Line no ' . $this->count . ' : ' : '';
            $fail($lineInfo . 'The selected techincal spec does not belong to the hardware standard.');
            return;
        }
    }
}
