<?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\ChangeStateCommand;
use Chill\TicketBundle\Action\Ticket\Handler\ChangeStateCommandHandler;
use Chill\TicketBundle\Entity\StateEnum;
use Chill\TicketBundle\Entity\Ticket;
use Doctrine\ORM\EntityManagerInterface;
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;

/**
 * Controller for changing the state of a ticket.
 */
final readonly class ChangeStateApiController
{
    public function __construct(
        private ChangeStateCommandHandler $changeStateCommandHandler,
        private Security $security,
        private EntityManagerInterface $entityManager,
        private SerializerInterface $serializer,
    ) {}

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

        $command = new ChangeStateCommand(StateEnum::CLOSED);
        $this->changeStateCommandHandler->__invoke($ticket, $command);

        $this->entityManager->flush();

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

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

        $command = new ChangeStateCommand(StateEnum::OPEN);
        $this->changeStateCommandHandler->__invoke($ticket, $command);

        $this->entityManager->flush();

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