<?php

declare(strict_types=1);

namespace App\Mcp\Tool\Site;

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

#[McpTool(
    name: 'list_sites',
    description: 'List all industrial sites with pagination. Sites contain machines. Filterable by name.',
)]
class ListSitesTool
{
    use McpToolHelper;

    public function __construct(
        private readonly SiteRepository $sites,
    ) {}

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

        $countQb = $this->sites->createQueryBuilder('s')
            ->select('COUNT(s.id)')
        ;

        $qb = $this->sites->createQueryBuilder('s')
            ->select('s.id', 's.name', 's.contactName', 's.contactCity', 's.contactPhone')
            ->orderBy('s.name', 'ASC')
        ;

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