<?php

declare(strict_types=1);

namespace App\Mcp\Tool\Composant;

use App\Entity\Composant;
use App\Entity\ComposantConstructeurLink;
use App\Mcp\Tool\McpToolHelper;
use App\Repository\ConstructeurRepository;
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: 'create_composant',
    description: 'Create a new composant. prix must be a string (e.g. "12.50"). Requires ROLE_GESTIONNAIRE.',
)]
class CreateComposantTool
{
    use McpToolHelper;

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

    /**
     * @param string[] $constructeurIds
     */
    public function __invoke(
        string $name,
        string $reference = '',
        string $description = '',
        string $prix = '',
        string $modelTypeId = '',
        array $constructeurIds = [],
    ): CallToolResult {
        $this->requireRole($this->security, 'ROLE_GESTIONNAIRE');

        $composant = new Composant();
        $composant->setName($name);

        if ('' !== $reference) {
            $composant->setReference($reference);
        }
        if ('' !== $description) {
            $composant->setDescription($description);
        }
        if ('' !== $prix) {
            $composant->setPrix($prix);
        }

        if ('' !== $modelTypeId) {
            $modelType = $this->modelTypes->find($modelTypeId);
            if (!$modelType) {
                $this->mcpError('not_found', "ModelType not found: {$modelTypeId}");
            }
            $composant->setTypeComposant($modelType);
        }

        foreach ($constructeurIds as $cId) {
            $c = $this->constructeurs->find($cId);
            if (!$c) {
                $this->mcpError('not_found', "Constructeur not found: {$cId}");
            }
            $link = new ComposantConstructeurLink();
            $link->setComposant($composant);
            $link->setConstructeur($c);
            $this->em->persist($link);
        }

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

        return $this->jsonResponse([
            'id'   => $composant->getId(),
            'name' => $composant->getName(),
        ]);
    }
}
