<?php

declare(strict_types=1);

namespace App\Mcp\Tool\Constructeur;

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

#[McpTool(
    name: 'list_constructeurs',
    description: 'List all constructeurs (manufacturers/suppliers) with pagination. Filterable by name.',
)]
class ListConstructeursTool
{
    use McpToolHelper;

    public function __construct(
        private readonly ConstructeurRepository $constructeurs,
    ) {}

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

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

        $qb = $this->constructeurs->createQueryBuilder('c')
            ->select('c.id', 'c.name', 'c.email')
            ->orderBy('c.name', 'ASC')
        ;

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