<?php

declare(strict_types=1);

namespace App\Mcp\Tool\Machine;

use App\Entity\MachineComponentLink;
use App\Entity\MachinePieceLink;
use App\Mcp\Tool\McpToolHelper;
use App\Repository\MachineComponentLinkRepository;
use App\Repository\MachinePieceLinkRepository;
use Doctrine\ORM\EntityManagerInterface;
use Mcp\Capability\Attribute\McpTool;
use Mcp\Schema\Result\CallToolResult;
use Symfony\Bundle\SecurityBundle\Security;

#[McpTool(
    name: 'update_machine_link',
    description: 'Update overrides (nameOverride, referenceOverride, prixOverride) or quantity on an existing machine link. Requires ROLE_GESTIONNAIRE.',
)]
class UpdateMachineLinkTool
{
    use McpToolHelper;

    public function __construct(
        private readonly EntityManagerInterface $em,
        private readonly Security $security,
        private readonly MachineComponentLinkRepository $componentLinks,
        private readonly MachinePieceLinkRepository $pieceLinks,
    ) {}

    public function __invoke(
        string $linkId,
        string $linkType,
        ?string $nameOverride = null,
        ?string $referenceOverride = null,
        ?string $prixOverride = null,
        ?int $quantity = null,
    ): CallToolResult {
        $this->requireRole($this->security, 'ROLE_GESTIONNAIRE');

        switch ($linkType) {
            case 'composant':
                $link = $this->componentLinks->find($linkId);
                if (null === $link) {
                    $this->mcpError('NotFound', "MachineComponentLink {$linkId} not found.");
                }

                $this->applyOverrides($link, $nameOverride, $referenceOverride, $prixOverride);
                $this->em->flush();

                return $this->jsonResponse([
                    'id'                => $link->getId(),
                    'type'              => 'composant',
                    'nameOverride'      => $link->getNameOverride(),
                    'referenceOverride' => $link->getReferenceOverride(),
                    'prixOverride'      => $link->getPrixOverride(),
                ]);

            case 'piece':
                $link = $this->pieceLinks->find($linkId);
                if (null === $link) {
                    $this->mcpError('NotFound', "MachinePieceLink {$linkId} not found.");
                }

                $this->applyOverrides($link, $nameOverride, $referenceOverride, $prixOverride);
                if (null !== $quantity) {
                    $link->setQuantity($quantity);
                }
                $this->em->flush();

                return $this->jsonResponse([
                    'id'                => $link->getId(),
                    'type'              => 'piece',
                    'nameOverride'      => $link->getNameOverride(),
                    'referenceOverride' => $link->getReferenceOverride(),
                    'prixOverride'      => $link->getPrixOverride(),
                    'quantity'          => $link->getQuantity(),
                ]);

            case 'product':
                $this->mcpError('Validation', 'Product links do not have updatable overrides.');

                // no break
            default:
                $this->mcpError('Validation', "Unknown link type '{$linkType}'. Expected composant, piece, or product.");
        }
    }

    private function applyOverrides(MachineComponentLink|MachinePieceLink $link, ?string $nameOverride, ?string $referenceOverride, ?string $prixOverride): void
    {
        if (null !== $nameOverride) {
            $link->setNameOverride($nameOverride);
        }
        if (null !== $referenceOverride) {
            $link->setReferenceOverride($referenceOverride);
        }
        if (null !== $prixOverride) {
            $link->setPrixOverride($prixOverride);
        }
    }
}
