<?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\Handler\ReplaceMotiveCommandHandler;
use Chill\TicketBundle\Action\Ticket\ReplaceMotiveCommand;
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\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;

final readonly class ReplaceMotiveController
{
    public function __construct(
        private Security $security,
        private ReplaceMotiveCommandHandler $replaceMotiveCommandHandler,
        private SerializerInterface $serializer,
        private ValidatorInterface $validator,
        private EntityManagerInterface $entityManager,
    ) {}

    #[Route('/api/1.0/ticket/{id}/motive/set', name: 'chill_ticket_motive_set', methods: ['POST'])]
    public function __invoke(Ticket $ticket, Request $request): Response
    {
        if (!$this->security->isGranted('ROLE_USER')) {
            throw new AccessDeniedHttpException('');
        }

        $command = $this->serializer->deserialize($request->getContent(), ReplaceMotiveCommand::class, 'json', [
            AbstractNormalizer::GROUPS => ['write'],
        ]);

        $errors = $this->validator->validate($command);

        if (0 < $errors->count()) {
            return new JsonResponse(
                $this->serializer->serialize($errors, 'json'),
                Response::HTTP_UNPROCESSABLE_ENTITY,
            );
        }

        $this->replaceMotiveCommandHandler->handle($ticket, $command);

        $this->entityManager->flush();

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