<?php

namespace App\Rules;

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

class MaxWordCount implements ValidationRule
{
    /**
     * @param int $max Maximum number of words allowed (default 7).
     */
    public function __construct(private readonly int $max = 7) {}

    /**
     * Run the validation rule.
     * Word count is determined by str_word_count() after stripping HTML tags.
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        $wordCount = str_word_count(strip_tags((string) $value));

        if ($wordCount > $this->max) {
            $fail("The :attribute must not exceed {$this->max} words (got {$wordCount}).");
        }
    }
}
