<?php

namespace Velis\Mvc\Controller\RestRequestHandler;

use Phalcon\Http\RequestInterface;
use Phalcon\Mvc\Dispatcher;
use Velis\App;
use Velis\App\PhalconVersion;
use Velis\Dto\Exceptions\ValidationException;
use Velis\Mvc\Controller\Exception\BadRequestException;
use Velis\Mvc\Controller\Utils\DtoRequestTransformer;

class ValidateDtoRequest extends AbstractRestRequestHandler
{
    private Dispatcher $dispatcher;

    public function __construct(Dispatcher $dispatcher = null)
    {
        $this->dispatcher = $dispatcher;
    }

    public function handle(RequestInterface $request): void
    {
        if (App::getPhalconMajorVersion() >= PhalconVersion::PHALCON5) {
            $requestTransformer = new DtoRequestTransformer($request);
            try {
                $requestTransformer->transformRequest($this->dispatcher);
            } catch (ValidationException $e) {
                $messages = implode('. ', array_map(fn ($error) => $error['message'], $e->getErrors()));
                throw new BadRequestException('Validation Error. ' . $messages);
            };
        }

        $this->handleNext($request);
    }
}
