<?php

declare(strict_types=1);

namespace UtilityModule\Handler;

use Doctrine\ORM\NoResultException;
use Psr\Http\Message\ServerRequestInterface;
use UtilityModule\Service\AuthService;
use Zend\Diactoros\Response\JsonResponse;

class AuthHandler extends AbstractCrudHandler
{
    /** @var AuthService */
    private $authService;

    public function __construct(AuthService $authService) {
        $this->authService = $authService;
    }

    /**
     * Respond to POST (login) requests
     * @param ServerRequestInterface $request
     * @return \Zend\Diactoros\Response\JsonResponse
     */
    public function create(ServerRequestInterface $request)
    {
        $data = $this->getRequestData($request);
        try {
            return new JsonResponse($this->authService->authenticate(
              $data['user'],
              $data['pass']
            ));
        } catch (NoResultException $e) {
            return new JsonResponse("Access denied", 401);
        }
    }

    /**
     * Respond to GET (renew-token) requests
     * @param ServerRequestInterface $request
     * @return \Zend\Diactoros\Response\JsonResponse
     */
    public function getList(ServerRequestInterface $request)
    {
        $token = $request->getAttribute('token');
        return new JsonResponse($this->authService->renewToken($token));
    }
}
