<?php

declare(strict_types=1);

namespace App\Mcp\Tool\ModelType;

use App\Entity\ModelType;
use App\Enum\ModelCategory;
use App\Mcp\Tool\McpToolHelper;
use Doctrine\ORM\EntityManagerInterface;
use Mcp\Capability\Attribute\McpTool;
use Mcp\Schema\Result\CallToolResult;
use Symfony\Bundle\SecurityBundle\Security;

#[McpTool(
    name: 'create_model_type',
    description: 'Create a new model type. Category must be one of: composant, piece, product. Requires ROLE_GESTIONNAIRE.',
)]
class CreateModelTypeTool
{
    use McpToolHelper;

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

    public function __invoke(string $name, string $category, string $code = ''): CallToolResult
    {
        $this->requireRole($this->security, 'ROLE_GESTIONNAIRE');

        $enumCategory = match (strtolower($category)) {
            'composant', 'component' => ModelCategory::COMPONENT,
            'piece'   => ModelCategory::PIECE,
            'product' => ModelCategory::PRODUCT,
            default   => null,
        };

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

        $mt = new ModelType();
        $mt->setName($name);
        $mt->setCategory($enumCategory);
        $mt->setCode('' !== $code ? $code : strtoupper(substr(str_replace(' ', '-', $name), 0, 20)).'-'.bin2hex(random_bytes(3)));

        $this->em->persist($mt);
        $this->em->flush();

        return $this->jsonResponse([
            'id'       => $mt->getId(),
            'name'     => $mt->getName(),
            'code'     => $mt->getCode(),
            'category' => $mt->getCategory()->value,
        ]);
    }
}
