<?php

declare(strict_types=1);

namespace App\Mcp\Tool\ModelType;

use App\Mcp\Tool\McpToolHelper;
use App\Repository\ModelTypeRepository;
use Doctrine\ORM\EntityManagerInterface;
use Mcp\Capability\Attribute\McpTool;
use Mcp\Schema\Result\CallToolResult;
use Symfony\Bundle\SecurityBundle\Security;

#[McpTool(
    name: 'update_model_type',
    description: 'Update an existing model type. Only provided fields are changed. Requires ROLE_GESTIONNAIRE.',
)]
class UpdateModelTypeTool
{
    use McpToolHelper;

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

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

        $mt = $this->modelTypes->find($modelTypeId);

        if (!$mt) {
            $this->mcpError('not_found', "ModelType not found: {$modelTypeId}");
        }

        if (null !== $name) {
            $mt->setName($name);
        }
        if (null !== $code) {
            $mt->setCode($code);
        }

        $this->em->flush();

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