<?php
namespace Newland\Toubiz\Sync\Neos\Controller;

use Neos\Flow\Property\Exception\TargetNotFoundException;
use Newland\Toubiz\Api\Redirect\RedirectHandler;
use Newland\Toubiz\Api\Redirect\RedirectHandlerFactory;
use Neos\Flow\Mvc\Controller\ActionController;
use Psr\Http\Message\ResponseInterface;

class RedirectController extends ActionController
{

    public function redirectTargetAction(string $type): string
    {
        $rawResponse = $this->handler($type)->handle($this->request->getHttpRequest());
        $this->mapPsrResponseToCurrentNeosResponse($rawResponse);
        return (string) $rawResponse->getBody();
    }

    private function handler(string $type): RedirectHandler
    {
        $handler = (new RedirectHandlerFactory())->getRedirectHandler($type);
        if (!$handler) {
            throw new TargetNotFoundException(
                sprintf('No redirect target "%s" found', $type)
            );
        }
        return $handler;
    }

    private function mapPsrResponseToCurrentNeosResponse(ResponseInterface $psrResponse): void
    {
        $this->response->setStatus(
            $psrResponse->getStatusCode(),
            $psrResponse->getReasonPhrase()
        );

        foreach ($psrResponse->getHeaders() as $name => $values) {
            $this->response->setHeader($name, $values, true);
        }
    }
}
