<?php

namespace Velis\Mvc\Controller\Listeners;

use Velis\Api\Client as ApiClient;
use Velis\Api\HttpExceptionHandler\HttpException;
use Velis\Api\Version;
use Velis\Mvc\Controller\Exception\NotFoundException;
use Velis\Mvc\Controller\Listeners\Concrete\AbstractListener;

class CheckApiVersionListener extends AbstractListener
{
    /**
     * @throws NotFoundException
     * @throws HttpException
     */
    public function handle(): void
    {
        // todo: To niech będzie sprawdzane tylko jak jest przesłany nagłówek z wersją. Może jakiś middleware do tego?
        $version = $this->dispatcher->getParam('version');
        if ($version) {
            if (!Version::validate($version)) {
                throw new NotFoundException('Unsupported API version');
            }
            $this->response->setHeader('X-Api-Version', $version);
        }

        $apiClient = new ApiClient($this->request);
        if (!$apiClient->checkMobileVersion()) {
            throw new HttpException('Upgrade Required', httpCode: 426);
        }
    }
}
