<?php

namespace App\Rules;

use App\ValueObjects\Email;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class EmailAddress implements ValidationRule
{
    /**
     * Run the validation rule.
     *
     * @param  \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (blank($value)) {
            return;
        }

        if (Email::tryFrom($value) === null) {
            $fail("The {$attribute} must be a valid email address.");
        }
    }
}
