<?php

declare(strict_types=1);

namespace App\Framework\LiveComponents\Validation;

/**
 * Result of state validation check
 *
 * Contains validation status and detailed error information.
 * Used for non-throwing validation checks.
 */
final readonly class ValidationResult
{
    /**
     * @param bool $valid Whether validation passed
     * @param array<string> $errors Validation error messages
     * @param array<string, string> $fieldErrors Field-specific errors
     */
    public function __construct(
        public bool $valid,
        public array $errors = [],
        public array $fieldErrors = []
    ) {
    }

    /**
     * Create successful validation result
     */
    public static function valid(): self
    {
        return new self(true, [], []);
    }

    /**
     * Create failed validation result
     *
     * @param array<string> $errors General errors
     * @param array<string, string> $fieldErrors Field-specific errors
     */
    public static function invalid(array $errors, array $fieldErrors = []): self
    {
        return new self(false, $errors, $fieldErrors);
    }

    /**
     * Check if validation passed
     */
    public function isValid(): bool
    {
        return $this->valid;
    }

    /**
     * Check if validation failed
     */
    public function isFailed(): bool
    {
        return ! $this->valid;
    }

    /**
     * Get all errors
     *
     * @return array<string>
     */
    public function getErrors(): array
    {
        return $this->errors;
    }

    /**
     * Get field-specific errors
     *
     * @return array<string, string>
     */
    public function getFieldErrors(): array
    {
        return $this->fieldErrors;
    }

    /**
     * Get error for specific field
     */
    public function getFieldError(string $field): ?string
    {
        return $this->fieldErrors[$field] ?? null;
    }

    /**
     * Check if field has error
     */
    public function hasFieldError(string $field): bool
    {
        return isset($this->fieldErrors[$field]);
    }

    /**
     * Get total error count
     */
    public function getErrorCount(): int
    {
        return count($this->errors) + count($this->fieldErrors);
    }
}
