<?php

declare(strict_types=1);

namespace App\Mcp\Tool\Product;

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

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

    public function __construct(
        private readonly ProductRepository $products,
    ) {}

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

        $countQb = $this->products->createQueryBuilder('pr')
            ->select('COUNT(pr.id)')
        ;

        $qb = $this->products->createQueryBuilder('pr')
            ->select('pr.id', 'pr.name', 'pr.reference', 'pr.supplierPrice')
            ->orderBy('pr.name', 'ASC')
        ;

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