<?php

declare(strict_types=1);

namespace App\Mcp\Tool\Composant;

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

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

    public function __construct(
        private readonly ComposantRepository $composants,
    ) {}

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

        $countQb = $this->composants->createQueryBuilder('c')
            ->select('COUNT(c.id)')
        ;

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

        if ('' !== $search) {
            $countQb->andWhere('LOWER(c.name) LIKE LOWER(:search) OR LOWER(c.reference) LIKE LOWER(:search)')
                ->setParameter('search', "%{$search}%")
            ;
            $qb->andWhere('LOWER(c.name) LIKE LOWER(:search) OR LOWER(c.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']);
    }
}
