<?php

declare(strict_types=1);

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

use App\Module\ProjectManagement\Domain\Repository\TaskRecurrenceRepositoryInterface;
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-recurrence', description: 'Delete a task recurrence pattern. Nullifies the recurrence on the active task and removes the recurring calendar event.')]
class DeleteTaskRecurrenceTool
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly TaskRecurrenceRepositoryInterface $taskRecurrenceRepository,
        private readonly Security $security,
        private readonly CalDavService $calDavService,
    ) {}

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

        $recurrence = $this->taskRecurrenceRepository->findById($recurrenceId);
        if (null === $recurrence) {
            throw new InvalidArgumentException(sprintf('TaskRecurrence with ID %d not found.', $recurrenceId));
        }

        $tasks = $recurrence->getTasks()->toArray();

        $eventUidToDelete = null;
        foreach ($tasks as $task) {
            if (null !== $task->getCalendarEventUid()) {
                $eventUidToDelete = $task->getCalendarEventUid();

                break;
            }
        }

        foreach ($tasks as $task) {
            $task->setRecurrence(null);
        }

        $this->entityManager->remove($recurrence);
        $this->entityManager->flush();

        if (null !== $eventUidToDelete) {
            $this->calDavService->deleteEvent($eventUidToDelete);
        }

        return json_encode([
            'success'      => true,
            'message'      => sprintf('TaskRecurrence %d deleted.', $recurrenceId),
            'tasksUpdated' => count($tasks),
        ]);
    }
}
