<?php

declare(strict_types=1);

namespace App\Module\ProjectManagement\Infrastructure\Mcp\Tool\Task;

use App\Module\ProjectManagement\Domain\Repository\TaskRepositoryInterface;
use App\Module\ProjectManagement\Infrastructure\Service\CalDavService;
use Doctrine\ORM\EntityManagerInterface;
use InvalidArgumentException;
use Mcp\Capability\Attribute\McpTool;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

use function sprintf;

#[McpTool(name: 'delete-task', description: 'Delete a task permanently. This also deletes all associated documents.')]
class DeleteTaskTool
{
    public function __construct(
        private readonly TaskRepositoryInterface $taskRepository,
        private readonly EntityManagerInterface $entityManager,
        private readonly Security $security,
        private readonly CalDavService $calDavService,
    ) {}

    public function __invoke(int $id): string
    {
        if (!$this->security->isGranted('ROLE_USER')) {
            throw new AccessDeniedException('Access denied: ROLE_USER required.');
        }

        $task = $this->taskRepository->findById($id);

        if (null === $task) {
            throw new InvalidArgumentException(sprintf('Task with ID %d not found.', $id));
        }

        $taskCode = $task->getProject()->getCode().'-'.$task->getNumber();
        $eventUid = $task->getCalendarEventUid();
        $todoUid  = $task->getCalendarTodoUid();
        $this->entityManager->remove($task);
        $this->entityManager->flush();

        if (null !== $eventUid) {
            $this->calDavService->deleteEvent($eventUid);
        }
        if (null !== $todoUid) {
            $this->calDavService->deleteTodo($todoUid);
        }

        return json_encode([
            'success' => true,
            'message' => sprintf('Task %s deleted.', $taskCode),
        ]);
    }
}
