<?php

declare(strict_types=1);

namespace App\Mcp\Tool\Composant;

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

#[McpTool(
    name: 'get_composant',
    description: 'Get a single composant by ID with all its details, including typeComposant and constructeurs.',
)]
class GetComposantTool
{
    use McpToolHelper;

    public function __construct(
        private readonly ComposantRepository $composants,
    ) {}

    public function __invoke(string $composantId): CallToolResult
    {
        $composant = $this->composants->find($composantId);

        if (!$composant) {
            $this->mcpError('not_found', "Composant not found: {$composantId}");
        }

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

        $typeComposant = null;
        if ($composant->getTypeComposant()) {
            $typeComposant = [
                'id'   => $composant->getTypeComposant()->getId(),
                'name' => $composant->getTypeComposant()->getName(),
            ];
        }

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