<?php

declare(strict_types=1);

namespace App\Mcp\Tool\Comment;

use App\Entity\Comment;
use App\Mcp\Tool\McpToolHelper;
use Doctrine\ORM\EntityManagerInterface;
use Mcp\Capability\Attribute\McpTool;
use Mcp\Schema\Result\CallToolResult;

#[McpTool(
    name: 'list_comments',
    description: 'List comments for a given entity (machine, piece, composant, product…) with pagination. Filter by entityType and entityId.',
)]
class ListCommentsTool
{
    use McpToolHelper;

    public function __construct(
        private readonly EntityManagerInterface $em,
    ) {}

    public function __invoke(string $entityType, string $entityId, int $page = 1, int $limit = 30): CallToolResult
    {
        $p = $this->paginationParams($page, $limit);

        $repo = $this->em->getRepository(Comment::class);

        $total = (int) $repo->createQueryBuilder('c')
            ->select('COUNT(c.id)')
            ->andWhere('c.entityType = :entityType')
            ->andWhere('c.entityId = :entityId')
            ->setParameter('entityType', $entityType)
            ->setParameter('entityId', $entityId)
            ->getQuery()
            ->getSingleScalarResult()
        ;

        $items = $repo->createQueryBuilder('c')
            ->select(
                'c.id',
                'c.content',
                'c.entityType',
                'c.entityId',
                'c.entityName',
                'c.authorName',
                'c.authorId',
                'c.status',
                'c.resolvedByName',
                'c.resolvedAt',
                'c.createdAt',
            )
            ->andWhere('c.entityType = :entityType')
            ->andWhere('c.entityId = :entityId')
            ->setParameter('entityType', $entityType)
            ->setParameter('entityId', $entityId)
            ->orderBy('c.createdAt', 'DESC')
            ->setFirstResult($p['offset'])
            ->setMaxResults($p['limit'])
            ->getQuery()
            ->getArrayResult()
        ;

        return $this->paginatedResponse($items, $total, $p['page'], $p['limit']);
    }
}
