<?php declare(strict_types=1);

namespace Newland\Toubiz\Sync\Neos\ErrorHandling;

use Neos\Error\Messages\Result;
use Neos\Flow\Validation\Error;
use Neos\Flow\Validation\Exception as NeosValidationException;

class ValidationException extends NeosValidationException
{
    /** @var string[] */
    protected $validationMessages = [];

    public function getValidationMessages(): array
    {
        return $this->validationMessages;
    }

    /**
     * @param string[] $validationMessages
     */
    public function setValidationMessages(array $validationMessages): void
    {
        $this->validationMessages = $validationMessages;
    }

    /**
     * @param object $entity
     */
    public static function forResult(Result $result, $entity): self
    {
        $messages = [];

        /** @var array<string, Error[]> */
        $flattenedErrors = $result->getFlattenedErrors();
        foreach ($flattenedErrors as $property => $errors) {
            $messagesForCurrentProperty = array_map(
                function (Error $error) {
                    return $error->render();
                },
                $errors
            );
            $messages[$property] = implode(', ', $messagesForCurrentProperty);
        }

        $classNameParts = explode('\\', \get_class($entity));
        $classBaseName = array_pop($classNameParts);

        $exception = new self(sprintf('Error validating %s', $classBaseName));
        $exception->setValidationMessages($messages);
        return $exception;
    }
}
