<?php
namespace Incoviba\Controller\API;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Ideal\Controller;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Exception\MissingAuthorizationHeader;
use Incoviba\Service;

class Tokens extends Controller
{
    use withJson;

    public function try(ServerRequestInterface $request, ResponseInterface $response,
                        Service\API $apiService,
                        Service\Login $loginService): ResponseInterface
    {
        $output = [
            'token' => '',
            'valid' => false
        ];
        try {
            $token = $apiService->getKey($request);
            $output['token'] = $token;
            if (!str_contains($token, $loginService->getSeparator())) {
                throw new EmptyResult('Token not complex');
            }
            list($key, $selector, $token) = explode($loginService->getSeparator(), $token, 3);
            $output['valid'] = $loginService->isIn($selector, $token);
        } catch (MissingAuthorizationHeader | EmptyResult) {}
        return $this->withJson($response, $output);
    }
}
