<?php declare(strict_types=1);

namespace idoit\Module\SyneticsFlows\Controller;

use GuzzleHttp\Psr7\Exception\MalformedUriException;
use idoit\Module\SyneticsFlows\Validation\ValidationMessage;
use Symfony\Component\HttpFoundation\Request;

class BaseController
{
    protected \isys_component_template_language_manager $language;

    /**
     * @throws \Exception
     */
    public function __construct()
    {
        $this->language = \isys_application::instance()->container->get('language');
    }

    /**
     * @param array $errors
     *
     * @return mixed
     * @throws \Exception
     */
    protected function translateErrorMessages(array $errors): mixed
    {
        return array_map(function ($error) {
            if ($error instanceof ValidationMessage) {
                return new ValidationMessage($error->getPath(), $this->language->get_in_text($error->getMessage()));
            }

            if (is_string($error)) {
                return $this->language->get_in_text($error);
            }

            return $error;
        }, $errors);
    }

    /**
     * @param Request $request
     *
     * @return array
     */
    protected function extractData(Request $request): array
    {
        $content = $request->getContent();

        if (!is_string($content)) {
            throw new MalformedUriException('Malformed JSON string');
        }

        return json_decode($content, true);
    }
}
