<?php

declare(strict_types=1);

namespace App\Mcp\Tool\CustomField;

use App\Entity\CustomFieldValue;
use App\Mcp\Tool\McpToolHelper;
use Doctrine\ORM\EntityManagerInterface;
use Mcp\Capability\Attribute\McpTool;
use Mcp\Schema\Result\CallToolResult;

#[McpTool(
    name: 'list_custom_field_values',
    description: 'List all custom field values for a given entity (machine, composant, piece or product). Returns each value with its custom field name and type.',
)]
class ListCustomFieldValuesTool
{
    use McpToolHelper;

    private const ALLOWED_TYPES = ['machine', 'composant', 'piece', 'product'];

    public function __construct(
        private readonly EntityManagerInterface $em,
    ) {}

    public function __invoke(string $entityType, string $entityId): CallToolResult
    {
        $entityType = strtolower($entityType);

        if (!in_array($entityType, self::ALLOWED_TYPES, true)) {
            $this->mcpError('validation', "entityType must be one of: machine, composant, piece, product. Got '{$entityType}'.");
        }

        $rows = $this->em->createQueryBuilder()
            ->select(
                'cfv.id',
                'cfv.value',
                'cf.id AS customFieldId',
                'cf.name AS customFieldName',
                'cf.type AS customFieldType',
                'cf.required AS customFieldRequired',
                'cfv.createdAt',
                'cfv.updatedAt',
            )
            ->from(CustomFieldValue::class, 'cfv')
            ->join('cfv.customField', 'cf')
            ->where("IDENTITY(cfv.{$entityType}) = :entityId")
            ->setParameter('entityId', $entityId)
            ->orderBy('cf.name', 'ASC')
            ->getQuery()
            ->getArrayResult()
        ;

        return $this->jsonResponse([
            'entityType' => $entityType,
            'entityId'   => $entityId,
            'values'     => $rows,
            'total'      => count($rows),
        ]);
    }
}
