<?php

declare(strict_types=1);

namespace App\Mcp\Tool\Machine;

use App\Mcp\Tool\McpToolHelper;
use App\Repository\MachineComponentLinkRepository;
use App\Repository\MachinePieceLinkRepository;
use App\Repository\MachineProductLinkRepository;
use App\Repository\MachineRepository;
use Mcp\Capability\Attribute\McpTool;
use Mcp\Schema\Result\CallToolResult;

#[McpTool(
    name: 'list_machine_links',
    description: 'List all links (component, piece, product) for a given machine, grouped by type.',
)]
class ListMachineLinksTool
{
    use McpToolHelper;

    public function __construct(
        private readonly MachineRepository $machines,
        private readonly MachineComponentLinkRepository $componentLinks,
        private readonly MachinePieceLinkRepository $pieceLinks,
        private readonly MachineProductLinkRepository $productLinks,
    ) {}

    public function __invoke(string $machineId): CallToolResult
    {
        $machine = $this->machines->find($machineId);
        if (null === $machine) {
            $this->mcpError('NotFound', "Machine {$machineId} not found.");
        }

        $compRows = $this->componentLinks->createQueryBuilder('cl')
            ->select('cl.id', 'IDENTITY(cl.composant) AS entityId', 'IDENTITY(cl.parentLink) AS parentLinkId', 'cl.nameOverride', 'cl.referenceOverride', 'cl.prixOverride')
            ->where('cl.machine = :machine')
            ->setParameter('machine', $machine)
            ->orderBy('cl.id', 'ASC')
            ->getQuery()
            ->getArrayResult()
        ;

        $pieceRows = $this->pieceLinks->createQueryBuilder('pl')
            ->select('pl.id', 'IDENTITY(pl.piece) AS entityId', 'IDENTITY(pl.parentLink) AS parentLinkId', 'pl.nameOverride', 'pl.referenceOverride', 'pl.prixOverride', 'pl.quantity')
            ->where('pl.machine = :machine')
            ->setParameter('machine', $machine)
            ->orderBy('pl.id', 'ASC')
            ->getQuery()
            ->getArrayResult()
        ;

        $productRows = $this->productLinks->createQueryBuilder('prl')
            ->select('prl.id', 'IDENTITY(prl.product) AS entityId', 'IDENTITY(prl.parentLink) AS parentLinkId', 'IDENTITY(prl.parentComponentLink) AS parentComponentLinkId', 'IDENTITY(prl.parentPieceLink) AS parentPieceLinkId')
            ->where('prl.machine = :machine')
            ->setParameter('machine', $machine)
            ->orderBy('prl.id', 'ASC')
            ->getQuery()
            ->getArrayResult()
        ;

        return $this->jsonResponse([
            'machineId'      => $machineId,
            'componentLinks' => $compRows,
            'pieceLinks'     => $pieceRows,
            'productLinks'   => $productRows,
        ]);
    }
}
