<?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\Pagination\PaginatorFactory;
use Chill\MainBundle\Serializer\Model\Collection;
use Chill\PersonBundle\Entity\SocialWork\SocialAction;
use Chill\PersonBundle\Repository\SocialWork\SocialIssueRepository;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

final class SocialWorkSocialActionApiController extends ApiController
{
    public function __construct(
        private readonly SocialIssueRepository $socialIssueRepository,
        private readonly PaginatorFactory $paginator,
        private readonly ClockInterface $clock,
    ) {}

    public function listBySocialIssueApi($id, Request $request)
    {
        $socialIssue = $this->socialIssueRepository
            ->find($id);

        if (null === $socialIssue) {
            throw $this->createNotFoundException('socialIssue not found');
        }

        $socialActions = SocialAction::filterRemoveDeactivatedActions(
            $socialIssue->getRecursiveSocialActions()->toArray(),
            \DateTime::createFromImmutable($this->clock->now())
        );

        usort($socialActions, static fn (SocialAction $sa, SocialAction $sb) => $sa->getOrdering() <=> $sb->getOrdering());

        $pagination = $this->paginator->create(\count($socialActions));
        // max one page
        $pagination->setItemsPerPage(\count($socialActions));

        $collection = new Collection($socialActions, $pagination);

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