<?php

declare(strict_types=1);

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

use App\Module\ProjectManagement\Domain\Repository\TaskGroupRepositoryInterface;
use App\Shared\Infrastructure\Mcp\Serializer;
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: 'update-group', description: 'Update an existing task group. Only provided fields are changed.')]
class UpdateGroupTool
{
    public function __construct(
        private readonly TaskGroupRepositoryInterface $taskGroupRepository,
        private readonly EntityManagerInterface $entityManager,
        private readonly Security $security,
    ) {}

    public function __invoke(
        int $id,
        ?string $title = null,
        ?string $description = null,
        ?string $color = null,
        ?bool $archived = null,
    ): string {
        if (!$this->security->isGranted('ROLE_USER')) {
            throw new AccessDeniedException('Access denied: ROLE_USER required.');
        }

        $group = $this->taskGroupRepository->findById($id);

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

        if (null !== $title) {
            $group->setTitle($title);
        }
        if (null !== $description) {
            $group->setDescription($description);
        }
        if (null !== $color) {
            $group->setColor($color);
        }
        if (null !== $archived) {
            $group->setArchived($archived);
        }

        $this->entityManager->flush();

        return json_encode(Serializer::groupFull($group));
    }
}
