<?php

declare(strict_types=1);

namespace App\Mcp\Tool\Piece;

use App\Mcp\Tool\McpToolHelper;
use App\Repository\PieceRepository;
use Mcp\Capability\Attribute\McpTool;
use Mcp\Schema\Result\CallToolResult;

#[McpTool(
    name: 'get_piece',
    description: 'Get a single piece by ID with all its details, including typePiece and constructeurs.',
)]
class GetPieceTool
{
    use McpToolHelper;

    public function __construct(
        private readonly PieceRepository $pieces,
    ) {}

    public function __invoke(string $pieceId): CallToolResult
    {
        $piece = $this->pieces->find($pieceId);

        if (!$piece) {
            $this->mcpError('not_found', "Piece not found: {$pieceId}");
        }

        $constructeurs = [];
        foreach ($piece->getConstructeurLinks() as $link) {
            $constructeurs[] = [
                'id'                => $link->getConstructeur()->getId(),
                'name'              => $link->getConstructeur()->getName(),
                'supplierReference' => $link->getSupplierReference(),
            ];
        }

        $typePiece = null;
        if ($piece->getTypePiece()) {
            $typePiece = [
                'id'   => $piece->getTypePiece()->getId(),
                'name' => $piece->getTypePiece()->getName(),
            ];
        }

        return $this->jsonResponse([
            'id'            => $piece->getId(),
            'name'          => $piece->getName(),
            'reference'     => $piece->getReference(),
            'description'   => $piece->getDescription(),
            'prix'          => $piece->getPrix(),
            'typePiece'     => $typePiece,
            'constructeurs' => $constructeurs,
            'createdAt'     => $piece->getCreatedAt()->format('Y-m-d H:i:s'),
            'updatedAt'     => $piece->getUpdatedAt()->format('Y-m-d H:i:s'),
        ]);
    }
}
