<?php

declare(strict_types=1);

namespace App\Mcp\Tool\Piece;

use App\Mcp\Tool\McpToolHelper;
use App\Repository\PieceRepository;
use Mcp\Capability\Attribute\McpTool;
use Mcp\Schema\Result\CallToolResult;

#[McpTool(
    name: 'list_pieces',
    description: 'List pieces with pagination. Filterable by name or reference.',
)]
class ListPiecesTool
{
    use McpToolHelper;

    public function __construct(
        private readonly PieceRepository $pieces,
    ) {}

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

        $countQb = $this->pieces->createQueryBuilder('pi')
            ->select('COUNT(pi.id)')
        ;

        $qb = $this->pieces->createQueryBuilder('pi')
            ->select('pi.id', 'pi.name', 'pi.reference', 'pi.prix')
            ->orderBy('pi.name', 'ASC')
        ;

        if ('' !== $search) {
            $countQb->andWhere('LOWER(pi.name) LIKE LOWER(:search) OR LOWER(pi.reference) LIKE LOWER(:search)')
                ->setParameter('search', "%{$search}%")
            ;
            $qb->andWhere('LOWER(pi.name) LIKE LOWER(:search) OR LOWER(pi.reference) LIKE LOWER(:search)')
                ->setParameter('search', "%{$search}%")
            ;
        }

        $total = (int) $countQb->getQuery()->getSingleScalarResult();

        $items = $qb->setFirstResult($p['offset'])
            ->setMaxResults($p['limit'])
            ->getQuery()
            ->getArrayResult()
        ;

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