<?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\Comment\Handler\UpdateCommentContentCommandHandlerInterface;
use Chill\TicketBundle\Action\Comment\UpdateCommentContentCommand;
use Chill\TicketBundle\Entity\Comment;
use Chill\TicketBundle\Security\Voter\CommentVoter;
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\SerializerInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;

final readonly class UpdateCommentController
{
    public function __construct(
        private Security $security,
        private SerializerInterface $serializer,
        private ValidatorInterface $validator,
        private UpdateCommentContentCommandHandlerInterface $updateCommentContentCommandHandler,
        private EntityManagerInterface $entityManager,
    ) {}

    #[Route('/api/1.0/ticket/comment/{id}/edit', name: 'chill_ticket_comment_edit', methods: ['POST'])]
    public function __invoke(Comment $comment, Request $request): Response
    {
        if (!$this->security->isGranted(CommentVoter::EDIT, $comment)) {
            throw new AccessDeniedHttpException('You are not allowed to edit this comment.');
        }

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

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

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

        $this->updateCommentContentCommandHandler->handle($comment, $command);

        $this->entityManager->flush();

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