<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class HostOrIpAddress implements ValidationRule
{
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        $host = rtrim(trim((string) $value), '.');
        if (filter_var($host, FILTER_VALIDATE_IP)) {
            return;
        }

        if (strlen($host) > 253 || ! preg_match('/^(?=.{1,253}$)(?:(?!-)[a-z0-9-]{1,63}(?<!-)\.)+(?!-)[a-z0-9-]{2,63}(?<!-)$/i', $host)) {
            $fail('The :attribute must be a valid IP address or hostname, for example core.ecomradeit.com.');
        }
    }
}
