<?php

namespace WPUltimateSecurity\UltimateSecurity\Support\Validation\Rules;

use WPUltimateSecurity\UltimateSecurity\Support\Validation\ValidationRuleInterface;

/**
 * Abstract Validation Rule
 *
 * Base class for validation rules providing common functionality.
 *
 * @package WPUltimateSecurity\UltimateSecurity\Support\Validation\Rules
 * @since 2.0.0
 */
abstract class AbstractRule implements ValidationRuleInterface
{
    /**
     * Custom error message.
     *
     * @var string|null
     */
    protected ?string $customMessage = null;

    /**
     * Set a custom error message.
     *
     * @param string $message The custom message.
     *
     * @return static
     */
    public function withMessage(string $message): static
    {
        $clone = clone $this;
        $clone->customMessage = $message;

        return $clone;
    }

    /**
     * Get the error message.
     *
     * @param string $field The field name.
     *
     * @return string
     */
    public function getMessage(string $field): string
    {
        if ($this->customMessage !== null) {
            return str_replace(':field', $field, $this->customMessage);
        }

        return $this->getDefaultMessage($field);
    }

    /**
     * Get the default error message.
     *
     * @param string $field The field name.
     *
     * @return string
     */
    abstract protected function getDefaultMessage(string $field): string;
}
