<?php

namespace App\Rules;

use App\Support\PhoneNormalizer;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class ValidPhone implements ValidationRule
{
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (! is_string($value)) {
            $fail("The {$attribute} must be a valid phone number.");

            return;
        }

        $normalized = PhoneNormalizer::normalize($value);
        $digits = $normalized ? preg_replace('/\D+/', '', $normalized) : '';

        // E.164 allows up to 15 digits. Seven is a pragmatic minimum for local numbers.
        if (! $digits || strlen($digits) < 7 || strlen($digits) > 15) {
            $fail("The {$attribute} must contain between 7 and 15 digits.");
        }
    }
}
