<?php

declare(strict_types=1);

namespace App\Mcp\Tool\Product;

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

#[McpTool(
    name: 'get_product',
    description: 'Get a single product by ID with all its details, including typeProduct and constructeurs.',
)]
class GetProductTool
{
    use McpToolHelper;

    public function __construct(
        private readonly ProductRepository $products,
    ) {}

    public function __invoke(string $productId): CallToolResult
    {
        $product = $this->products->find($productId);

        if (!$product) {
            $this->mcpError('not_found', "Product not found: {$productId}");
        }

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

        $typeProduct = null;
        if ($product->getTypeProduct()) {
            $typeProduct = [
                'id'   => $product->getTypeProduct()->getId(),
                'name' => $product->getTypeProduct()->getName(),
            ];
        }

        return $this->jsonResponse([
            'id'            => $product->getId(),
            'name'          => $product->getName(),
            'reference'     => $product->getReference(),
            'supplierPrice' => $product->getSupplierPrice(),
            'typeProduct'   => $typeProduct,
            'constructeurs' => $constructeurs,
            'createdAt'     => $product->getCreatedAt()->format('Y-m-d H:i:s'),
            'updatedAt'     => $product->getUpdatedAt()->format('Y-m-d H:i:s'),
        ]);
    }
}
