<?php

/**
 * Валидатор входных данных
 *
 * @package Flowaxy\Infrastructure\Security\Validators
 * @version 1.0.0 Alpha prerelease
 */

declare(strict_types=1);

namespace Flowaxy\Infrastructure\Security\Validators;

use Flowaxy\Support\Services\ValidationService;

class InputValidator
{
    /**
     * Получение экземпляра ValidationService
     *
     * @return ValidationService
     */
    private function getValidationService(): ValidationService
    {
        static $service = null;
        if ($service === null) {
            $service = new ValidationService();
        }
        return $service;
    }
    /**
     * Валидация входных данных
     *
     * @param array<string, mixed> $data Данные для валидации
     * @param array<string, array<string>> $rules Правила валидации
     * @return array<string, string> Ошибки валидации
     */
    public function validate(array $data, array $rules): array
    {
        $errors = [];

        foreach ($rules as $field => $fieldRules) {
            $value = $data[$field] ?? null;

            foreach ($fieldRules as $rule) {
                if (!$this->validateRule($value, $rule)) {
                    $errors[$field] = "Field {$field} failed validation rule: {$rule}";
                    break;
                }
            }
        }

        return $errors;
    }

    private function validateRule(mixed $value, string $rule): bool
    {
        $validationService = $this->getValidationService();

        return match ($rule) {
            'required' => $value !== null && $value !== '',
            'email' => $validationService->validateEmail((string)$value)['valid'] ?? false,
            'numeric' => is_numeric($value),
            default => true,
        };
    }
}
