<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\PersonBundle\Controller;

use Chill\MainBundle\CRUD\Controller\ApiController;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Serializer\Model\Collection;
use Chill\MainBundle\Serializer\Model\Counter;
use Chill\PersonBundle\Repository\AccompanyingPeriod\AccompanyingPeriodWorkRepository;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;

class AccompanyingCourseWorkApiController extends ApiController
{
    public function __construct(
        private readonly AccompanyingPeriodWorkRepository $accompanyingPeriodWorkRepository,
        private readonly Security $security,
    ) {}

    #[Route(path: '/api/1.0/person/accompanying-period/work/my-near-end')]
    public function myWorksNearEndDate(Request $request): JsonResponse
    {
        $user = $this->security->getUser();

        if (!$user instanceof User) {
            throw new AccessDeniedHttpException();
        }

        $since = (new \DateTimeImmutable('now'))
            ->sub(new \DateInterval('P'.$request->query->getInt('since', 15).'D'));
        $until = (new \DateTimeImmutable('now'))
            ->add(new \DateInterval('P'.$request->query->getInt('since', 15).'D'));
        $total = $this->accompanyingPeriodWorkRepository
            ->countNearEndDateByUser($user, $since, $until);

        if ($request->query->getBoolean('countOnly', false)) {
            return $this->json(
                new Counter($total),
                JsonResponse::HTTP_OK,
                [],
                ['groups' => ['read']]
            );
        }

        $paginator = $this->getPaginatorFactory()->create($total);
        $works = $this->accompanyingPeriodWorkRepository
            ->findNearEndDateByUser($user, $since, $until, $paginator->getItemsPerPage(), $paginator->getCurrentPageFirstItemNumber());

        $collection = new Collection($works, $paginator);

        return $this->json($collection, 200, [], ['groups' => ['read']]);
    }

    protected function getContextForSerialization(string $action, Request $request, string $_format, $entity): array
    {
        switch ($action) {
            case '_entity':
                switch ($request->getMethod()) {
                    case Request::METHOD_PUT:
                        return ['groups' => ['accompanying_period_work:edit']];
                }
        }

        return parent::getContextForSerialization($action, $request, $_format, $entity);
    }
}
