<?php

declare(strict_types=1);

namespace App\Handler\Api;

use App\Service\AwardeeManager;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use UtilityModule\Handler\AbstractCrudHandler;
use Zend\Diactoros\Response\JsonResponse;

class AwardeeHandler extends AbstractCrudHandler
{
    /** @var AwardeeManager */
    private $awardeeManager;

    public function __construct(
        AwardeeManager $awardeeManager
    ) {
        $this->awardeeManager = $awardeeManager;
    }

    /**
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function getList(ServerRequestInterface $request): ResponseInterface
    {
        $entities = $this->awardeeManager->getAwardees();
        return new JsonResponse($entities);
    }

    /**
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     */
    public function get(ServerRequestInterface $request): ResponseInterface
    {
        $id = $request->getAttribute(static::IDENTIFIER_NAME);
        $entity = $this->awardeeManager->getAwardee((int)$id);
        return new JsonResponse($entity);
    }

    /**
     * @param ServerRequestInterface $request
     * @return JsonResponse
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function create(ServerRequestInterface $request): ResponseInterface
    {
        $data = $this->getRequestData($request);
        $entity = $this->awardeeManager->create($data);
        return new JsonResponse($entity);
    }

    /**
     * @param ServerRequestInterface $request
     * @return JsonResponse
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function update(ServerRequestInterface $request): ResponseInterface
    {
        $id = $request->getAttribute(static::IDENTIFIER_NAME);
        $data = $this->getRequestData($request);
        $entity = $this->awardeeManager->update((int)$id, $data);
        return new JsonResponse($entity);
    }

    /**
     * @param ServerRequestInterface $request
     * @return ResponseInterface
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function delete(ServerRequestInterface $request): ResponseInterface
    {
        $id = $request->getAttribute(static::IDENTIFIER_NAME);
        return new JsonResponse($this->awardeeManager->delete((int)$id));
    }
}
