<?php

declare(strict_types=1);

namespace Gls\GlsPoland\Controller\Api;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
use Symfony\Component\Serializer\Encoder\DecoderInterface;
use Symfony\Component\Serializer\Encoder\EncoderInterface;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;

/**
 * @deprecated
 */
abstract class AbstractApiController extends AbstractController
{
    private $decoder;
    private $encoder;

    public function __construct(DecoderInterface $decoder, EncoderInterface $encoder)
    {
        $this->decoder = $decoder;
        $this->encoder = $encoder;
    }

    protected function submitForm(FormInterface $form, Request $request): void
    {
        $data = $this->decode($request);
        $form->submit($data, Request::METHOD_PATCH !== $request->getMethod());

        if (!$form->isValid()) {
            throw new UnprocessableEntityHttpException($this->encode(['errors' => $this->getFormErrors($form)]));
        }
    }

    private function getFormErrors(FormInterface $form): array
    {
        $errors = [];
        foreach ($form->getErrors() as $error) {
            $errors[] = $error->getMessage();
        }

        /** @var FormInterface $child */
        foreach ($form as $child) {
            if ($childErrors = $this->getFormErrors($child)) {
                $errors[$child->getName()] = $childErrors;
            }
        }

        return $errors;
    }

    private function decode(Request $request): array
    {
        try {
            $data = $this->decoder->decode($request->getContent(), JsonEncoder::FORMAT, [
                'json_decode_associative' => true,
                'json_decode_options' => \JSON_BIGINT_AS_STRING,
            ]);
        } catch (UnexpectedValueException $e) {
            throw new BadRequestHttpException($this->encode(['errors' => ['Malformed request']]), $e);
        }

        if (!is_array($data)) {
            throw new BadRequestHttpException($this->encode(['errors' => ['Malformed request']]));
        }

        return $data;
    }

    protected function encode($data): string
    {
        return $this->encoder->encode($data, JsonEncoder::FORMAT);
    }
}
