<?php

declare(strict_types=1);

namespace App\Handler;

use App\Entity\Awardee;
use Doctrine\ORM\EntityManager;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Zend\Diactoros\Response\RedirectResponse;
use Zend\Expressive\Helper\UrlHelper;

class AwardeeRedirectHandler implements RequestHandlerInterface
{
    /** @var UrlHelper  */
    private $urlHelper;

    /** @var EntityManager */
    private $entityManager;

    public function __construct(
        UrlHelper $urlHelper,
        EntityManager $entityManager
    ) {
        $this->urlHelper = $urlHelper;
        $this->entityManager = $entityManager;
    }

    /**
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     * @throws \Doctrine\ORM\NonUniqueResultException
     */
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $qb = $this->entityManager->createQueryBuilder();
        $maxYear = $qb->select('max(a.year)')
            ->from(Awardee::class, 'a')
            ->getQuery()
            ->getSingleScalarResult();

        $url = $this->urlHelper->generate('awardees-by-year', [
            'year' => $maxYear,
        ]);
        return new RedirectResponse($url);
    }
}
