<?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\TicketBundle\Controller;

use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Security\Authorization\AuthorizationHelperForCurrentUserInterface;
use Chill\PersonBundle\Security\Authorization\PersonVoter;
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;

/**
 * Give a list of Centers usable for searching amongst tickets.
 */
final readonly class CenterForTicketListApiController
{
    public function __construct(
        private AuthorizationHelperForCurrentUserInterface $authorizationHelperForCurrentUser,
        private Security $security,
        private SerializerInterface $serializer,
    ) {}

    #[Route(path: '/api/1.0/ticket/search/authorized-centers')]
    public function __invoke(): JsonResponse
    {
        $user = $this->security->getUser();

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

        $centers = $this->authorizationHelperForCurrentUser->getReachableCenters(PersonVoter::SEE);

        return new JsonResponse(
            $this->serializer->serialize($centers, 'json', ['groups' => 'read']),
            Response::HTTP_OK,
            json: true
        );
    }
}
