<?php

declare(strict_types=1);

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

use App\Module\ProjectManagement\Domain\Repository\TaskRepositoryInterface;
use App\Shared\Infrastructure\Mcp\Serializer;
use InvalidArgumentException;
use Mcp\Capability\Attribute\McpTool;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

use function sprintf;

#[McpTool(name: 'get-task', description: 'Get full task details including description, all relations, and documents')]
class GetTaskTool
{
    public function __construct(
        private readonly TaskRepositoryInterface $taskRepository,
        private readonly Security $security,
    ) {}

    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));
        }

        return json_encode([
            'id'            => $task->getId(),
            'number'        => $task->getNumber(),
            'title'         => $task->getTitle(),
            'description'   => $task->getDescription(),
            'status'        => Serializer::statusFull($task->getStatus()),
            'priority'      => Serializer::priority($task->getPriority()),
            'effort'        => Serializer::effort($task->getEffort()),
            'assignee'      => Serializer::user($task->getAssignee()),
            'collaborators' => Serializer::users($task->getCollaborators()),
            'group'         => Serializer::group($task->getGroup()),
            'project'       => Serializer::projectRef($task->getProject()),
            'tags'          => Serializer::tagsWithColor($task->getTags()),
            'documents'     => Serializer::documents($task->getDocuments()),
            'archived'      => $task->isArchived(),
        ]);
    }
}
