<?php

namespace Comitium5\DesignerBundle\Resolver\Page;

use Comitium5\DesignerBundle\Entity\Page;
use Comitium5\DesignerBundle\Validator\EntityValidator;
use Comitium5\DesignerBundle\Validator\EntityValidatorConstraintInterface;
use Comitium5\DesignerBundle\Validator\Page\PageHasRelatedTemplateConstraint;
use Comitium5\DesignerBundle\ValueObjects\Common\ErrorObject;

/**
 * Class PageValidationResolver
 *
 * Joan Pont <joan.pont@bab-soft.com>
 * @package Comitium5\DesignerBundle\Resolver\Page
 */
class PageValidationResolver
{
    /**
     * @var EntityValidator
     */
    private $entityValidator;

    /**
     * PageValidationResolver constructor.
     *
     * @param EntityValidator $entityValidator
     */
    public function __construct(EntityValidator $entityValidator)
    {
        $this->entityValidator = $entityValidator;
    }

    /**
     * @param Page|null $page
     * @param EntityValidatorConstraintInterface[] $constraints
     *
     * @return ErrorObject
     */
    public function __invoke(Page $page = null, array $constraints = []): ErrorObject
    {
        if (empty($page)) {
            return new ErrorObject(
                404,
                "common.errors.page.404",
                false
            );
        }

        $constraints = $this->mergeWithDefaultConstraints($constraints);

        $result = $this->entityValidator->validate($page, $constraints);

        return new ErrorObject(
            422,
            $result->getErrorMessage(),
            $result->isValidResult()
        );
    }

    /**
     * @param EntityValidatorConstraintInterface[] $constraints
     *
     * @return array
     */
    protected function mergeWithDefaultConstraints(array $constraints): array
    {
        return array_merge($constraints, [
            new PageHasRelatedTemplateConstraint(),
        ]);
    }
}
