<?php

declare(strict_types=1);

namespace App\Handler;

use App\Service\AwardeeManager;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Zend\Diactoros\Response\HtmlResponse;
use Zend\Diactoros\Response\RedirectResponse;
use Zend\Expressive\Helper\UrlHelper;
use Zend\Expressive\Template\TemplateRendererInterface;

class AwardeeHandler implements RequestHandlerInterface
{
    /** @var TemplateRendererInterface */
    private $template;

    /** @var AwardeeManager */
    private $awardeeManager;

    /** @var UrlHelper */
    private $urlHelper;

    public function __construct(
        TemplateRendererInterface $template,
        AwardeeManager $awardeeManager,
        UrlHelper $urlHelper
    )
    {
        $this->template = $template;
        $this->awardeeManager = $awardeeManager;
        $this->urlHelper = $urlHelper;
    }

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $year = $request->getAttribute('year');
        $awardees = $this->awardeeManager->getJudgesByYear((int)$year);

        if (count($awardees) === 1) {
            $url = $this->urlHelper->generate('awardee', [
                'slug' => $awardees[0]->getSlug(),
            ]);
            return new RedirectResponse($url);
        }

        return new HtmlResponse($this->template->render("app::awardees", [
            'year' => $year,
            'awardees' => $awardees,
        ]));
    }
}
