<?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\TicketBundle\Entity\Ticket;
use Chill\TicketBundle\Service\Ticket\SuggestPersonForTicketInterface;
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 SuggestPersonForTicketApiController
{
    public function __construct(
        private SuggestPersonForTicketInterface $suggestPersonForTicket,
        private SerializerInterface $serializer,
        private Security $security,
    ) {}

    #[Route('/api/1.0/ticket/ticket/{id}/suggest-person', name: 'chill_ticket_ticket_suggest_person_api', requirements: ['id' => '\d+'], methods: ['GET'])]
    public function __invoke(Ticket $ticket): Response
    {
        if (!$this->security->isGranted('ROLE_USER')) {
            throw new AccessDeniedHttpException('Only users are allowed to suggest persons for tickets.');
        }

        $persons = $this->suggestPersonForTicket->suggestPerson($ticket, 0, 10);

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