<?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\ChangeEmergencyStateCommand;
use Chill\TicketBundle\Action\Ticket\Handler\ChangeEmergencyStateCommandHandler;
use Chill\TicketBundle\Entity\EmergencyStatusEnum;
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 emergency status of a ticket.
 */
final readonly class ChangeEmergencyStateApiController
{
    public function __construct(
        private ChangeEmergencyStateCommandHandler $changeEmergencyStateCommandHandler,
        private Security $security,
        private EntityManagerInterface $entityManager,
        private SerializerInterface $serializer,
    ) {}

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

        $command = new ChangeEmergencyStateCommand(EmergencyStatusEnum::YES);
        $this->changeEmergencyStateCommandHandler->__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}/emergency/no', name: 'chill_ticket_ticket_emergency_no_api', requirements: ['id' => '\d+'], methods: ['POST'])]
    public function setEmergencyNo(Ticket $ticket): Response
    {
        if (!$this->security->isGranted('ROLE_USER')) {
            throw new AccessDeniedHttpException('Only users are allowed to set emergency status to NO.');
        }

        $command = new ChangeEmergencyStateCommand(EmergencyStatusEnum::NO);
        $this->changeEmergencyStateCommandHandler->__invoke($ticket, $command);

        $this->entityManager->flush();

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