<?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\Pagination\PaginatorFactoryInterface;
use Chill\MainBundle\Serializer\Model\Collection;
use Chill\PersonBundle\PersonIdentifier\PersonIdentifierManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Serializer\SerializerInterface;

final readonly class PersonIdentifierListApiController
{
    public function __construct(
        private Security $security,
        private SerializerInterface $serializer,
        private PersonIdentifierManagerInterface $personIdentifierManager,
        private PaginatorFactoryInterface $paginatorFactory,
    ) {}

    #[Route('/api/1.0/person/identifiers/workers', name: 'person_person_identifiers_worker_list')]
    public function list(): Response
    {
        if (!$this->security->isGranted('ROLE_USER')) {
            throw new AccessDeniedHttpException();
        }

        $workers = $this->personIdentifierManager->getWorkers();
        $paginator = $this->paginatorFactory->create(count($workers));
        $paginator->setItemsPerPage(count($workers));
        $collection = new Collection($workers, $paginator);

        return new JsonResponse($this->serializer->serialize($collection, 'json'), json: true);
    }
}
