<?php
namespace PpPhp\Plugins;

use PpPhp\Core\ValidationPlugin;

class LengthRule implements ValidationPlugin
{
    public static function id(): string { return 'length'; }
    public static function label(): string { return 'Text length'; }
    public static function group(): string { return 'Length'; }

    public static function paramsSchema(): array
    {
        return [
            ['key' => 'min', 'type' => 'number', 'label' => 'Min characters', 'default' => ''],
            ['key' => 'max', 'type' => 'number', 'label' => 'Max characters', 'default' => ''],
        ];
    }

    public static function appliesTo(): array { return ['text', 'password', 'textarea']; }
    public static function defaultMessage(): string { return 'Length is out of range.'; }

    public static function serverCheck(mixed $value, array $params, array $record = []): bool
    {
        $len = mb_strlen((string) $value);
        if (($params['min'] ?? '') !== '' && is_numeric($params['min']) && $len < (int) $params['min']) return false;
        if (($params['max'] ?? '') !== '' && is_numeric($params['max']) && $len > (int) $params['max']) return false;
        return true;
    }

    public static function clientRule(array $params): array
    {
        $rule = [];
        if (($params['min'] ?? '') !== '' && is_numeric($params['min'])) $rule['minLength'] = (int) $params['min'];
        if (($params['max'] ?? '') !== '' && is_numeric($params['max'])) $rule['maxLength'] = (int) $params['max'];
        return $rule;
    }
}
