<?php

declare(strict_types=1);

namespace App\Mcp\Tool\ModelType;

use App\Enum\ModelCategory;
use App\Mcp\Tool\McpToolHelper;
use App\Repository\ModelTypeRepository;
use Mcp\Capability\Attribute\McpTool;
use Mcp\Schema\Result\CallToolResult;

#[McpTool(
    name: 'list_model_types',
    description: 'List model types with pagination. Filterable by category (composant, piece, product).',
)]
class ListModelTypesTool
{
    use McpToolHelper;

    public function __construct(
        private readonly ModelTypeRepository $modelTypes,
    ) {}

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

        $countQb = $this->modelTypes->createQueryBuilder('mt')
            ->select('COUNT(mt.id)')
        ;

        $qb = $this->modelTypes->createQueryBuilder('mt')
            ->select('mt.id', 'mt.name', 'mt.code', 'mt.category')
            ->orderBy('mt.name', 'ASC')
        ;

        if ('' !== $category) {
            $enumCategory = $this->resolveCategory($category);

            if (null === $enumCategory) {
                $this->mcpError('validation', "Invalid category '{$category}'. Must be one of: composant, piece, product.");
            }

            $countQb->andWhere('mt.category = :category')
                ->setParameter('category', $enumCategory)
            ;
            $qb->andWhere('mt.category = :category')
                ->setParameter('category', $enumCategory)
            ;
        }

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

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

        // Convert ModelCategory enum to string in results
        foreach ($items as &$item) {
            if ($item['category'] instanceof ModelCategory) {
                $item['category'] = $item['category']->value;
            }
        }

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

    private function resolveCategory(string $category): ?ModelCategory
    {
        return match (strtolower($category)) {
            'composant', 'component' => ModelCategory::COMPONENT,
            'piece'   => ModelCategory::PIECE,
            'product' => ModelCategory::PRODUCT,
            default   => null,
        };
    }
}
