<?php

declare(strict_types=1);

namespace App\Mcp\Tool\Machine;

use App\Entity\MachineConstructeurLink;
use App\Mcp\Tool\McpToolHelper;
use App\Repository\ConstructeurRepository;
use App\Repository\MachineRepository;
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: 'update_machine',
    description: 'Update an existing machine. Only provided fields are changed. prix must be a string. Requires ROLE_GESTIONNAIRE.',
)]
class UpdateMachineTool
{
    use McpToolHelper;

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

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

        $machine = $this->machines->find($machineId);

        if (!$machine) {
            $this->mcpError('not_found', "Machine not found: {$machineId}");
        }

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

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

        if (null !== $constructeurIds) {
            foreach ($machine->getConstructeurLinks()->toArray() as $existing) {
                $this->em->remove($existing);
            }
            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->flush();

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