<?php

declare(strict_types=1);

namespace App\Mcp\Tool\Machine;

use App\Entity\Machine;
use App\Entity\MachineConstructeurLink;
use App\Mcp\Tool\McpToolHelper;
use App\Repository\ConstructeurRepository;
use App\Repository\SiteRepository;
use Doctrine\ORM\EntityManagerInterface;
use Mcp\Capability\Attribute\McpTool;
use Mcp\Schema\Result\CallToolResult;
use Symfony\Bundle\SecurityBundle\Security;

#[McpTool(
    name: 'create_machine',
    description: 'Create a new machine. siteId is required. prix must be a string (e.g. "12.50"). Requires ROLE_GESTIONNAIRE.',
)]
class CreateMachineTool
{
    use McpToolHelper;

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

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

        $site = $this->sites->find($siteId);
        if (!$site) {
            $this->mcpError('not_found', "Site not found: {$siteId}");
        }

        $machine = new Machine();
        $machine->setName($name);
        $machine->setSite($site);

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

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

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

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