<?php
namespace Incoviba\Controller\API;

use Incoviba\Common\Implement\Exception\EmptyResult;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Repository;
use Incoviba\Service;
use Psr\Log\LoggerInterface;

class Login
{
    use withJson;

    public function __invoke(ServerRequestInterface $request, ResponseInterface $response,
                             Repository\User $userRepository,
                             Repository\Login $loginRepository,
                             Service\Login $loginService): ResponseInterface
    {
        $body = $request->getParsedBody();
        $output = [
            'username' => $body['username'],
        ];
        try {
            $user = $userRepository->fetchByName($body['username']);
            if ($user->validate($body['password'])) {
                $loginService->login($user);
                $output['token'] = $loginService->getToken();
            }
        } catch (EmptyResult) {}
        return $this->withJson($response, $output);
    }
}
