<?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\Action\Ticket\SetCallerCommand;
use Chill\TicketBundle\Action\Ticket\Handler\SetCallerCommandHandler;
use Chill\TicketBundle\Entity\Ticket;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Serializer\SerializerInterface;

/**
 * Controller for setting the caller of a ticket.
 */
final readonly class SetCallerApiController
{
    public function __construct(
        private SetCallerCommandHandler $setCallerCommandHandler,
        private Security $security,
        private EntityManagerInterface $entityManager,
        private SerializerInterface $serializer,
    ) {}

    #[Route('/api/1.0/ticket/ticket/{id}/set-caller', name: 'chill_ticket_ticket_set_caller_api', requirements: ['id' => '\d+'], methods: ['POST'])]
    public function setCaller(Ticket $ticket, Request $request): Response
    {
        if (!$this->security->isGranted('ROLE_USER')) {
            throw new AccessDeniedHttpException('Only users are allowed to set ticket callers.');
        }

        try {
            /** @var SetCallerCommand $command */
            $command = $this->serializer->deserialize(
                $request->getContent(),
                SetCallerCommand::class,
                'json'
            );
        } catch (\Throwable $e) {
            throw new BadRequestHttpException('Invalid request body: '.$e->getMessage(), $e);
        }

        $this->setCallerCommandHandler->__invoke($ticket, $command);

        $this->entityManager->flush();

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