<?php

namespace ZenoChatbot\Framework\Validation;

class ValidationException extends \Exception
{
    /**
     * @var array<string, array<int, string>>
     */
    protected array $errors = [];

    /**
     * @param string $message
     * @param array<string, array<int, string>> $errors
     * @param int $code
     * @param \Throwable|null $previous
     */
    public function __construct(string $message = 'The given data was invalid.', array $errors = [], int $code = 422, ?\Throwable $previous = null)
    {
        parent::__construct($message, $code, $previous);
        $this->errors = $errors;
    }

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

    /**
     * Get the first error message for each attribute
     *
     * @return array<string, string>
     */
    public function firstErrors(): array
    {
        $first = [];
        foreach ($this->errors as $key => $messages) {
            if (!empty($messages)) {
                $first[$key] = $messages[0];
            }
        }
        return $first;
    }
}
