<?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\UpdateCommentDeletedStatusCommandHandlerInterface;
use Chill\TicketBundle\Action\Comment\UpdateCommentDeletedStatusCommand;
use Chill\TicketBundle\Entity\Comment;
use Chill\TicketBundle\Security\Voter\CommentVoter;
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;

final readonly class UpdateCommentDeletedStatusController
{
    public function __construct(
        private Security $security,
        private SerializerInterface $serializer,
        private UpdateCommentDeletedStatusCommandHandlerInterface $updateCommentDeletedStatusCommandHandler,
        private EntityManagerInterface $entityManager,
    ) {}

    #[Route('/api/1.0/ticket/comment/{id}/delete', name: 'chill_ticket_comment_delete', methods: ['POST'])]
    public function deleteComment(Comment $comment): Response
    {
        return $this->updateCommentDeletedStatus($comment, true);
    }

    #[Route('/api/1.0/ticket/comment/{id}/restore', name: 'chill_ticket_comment_restore', methods: ['POST'])]
    public function restoreComment(Comment $comment): Response
    {
        return $this->updateCommentDeletedStatus($comment, false);
    }

    private function updateCommentDeletedStatus(Comment $comment, bool $delete): Response
    {
        if (!$this->security->isGranted(CommentVoter::EDIT, $comment)) {
            throw new AccessDeniedHttpException('You are not allowed to edit this comment.');
        }

        $command = new UpdateCommentDeletedStatusCommand(delete: $delete);

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

        $this->entityManager->flush();

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