<?php
namespace PpPhp\Plugins;

use PpPhp\Core\ValidationPlugin;

class InListRule implements ValidationPlugin
{
    public static function id(): string { return 'inList'; }
    public static function label(): string { return 'One of a list'; }
    public static function group(): string { return 'Data'; }

    public static function paramsSchema(): array
    {
        return [
            ['key' => 'values', 'type' => 'text', 'label' => 'Allowed values (comma-separated)', 'default' => '', 'placeholder' => 'active, inactive, pending'],
            ['key' => 'ci', 'type' => 'bool', 'label' => 'Ignore case', 'default' => true],
        ];
    }

    public static function appliesTo(): array { return ['text', 'select']; }
    public static function defaultMessage(): string { return 'Choose one of the allowed values.'; }

    private static function flag(mixed $v): bool { return in_array(strtolower((string) $v), ['1', 'yes', 'true', 'on'], true); }

    /** @return string[] */
    private static function parse(string $csv): array
    {
        return array_values(array_filter(array_map('trim', explode(',', $csv)), 'strlen'));
    }

    public static function serverCheck(mixed $value, array $params, array $record = []): bool
    {
        $list = self::parse((string) ($params['values'] ?? ''));
        if ($list === []) return true; // nothing configured → nothing to fail
        $v = (string) $value;
        if (self::flag($params['ci'] ?? true)) {
            $v = mb_strtolower($v);
            $list = array_map('mb_strtolower', $list);
        }
        return in_array($v, $list, true);
    }

    public static function clientRule(array $params): array
    {
        $list = self::parse((string) ($params['values'] ?? ''));
        if ($list === []) return [];
        return ['in' => $list, 'ci' => self::flag($params['ci'] ?? true)];
    }
}
