<?php

declare(strict_types=1);

namespace App\Mcp\Tool\Machine;

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

#[McpTool(
    name: 'get_machine',
    description: 'Get a single machine by ID with all its details, including site and constructeurs.',
)]
class GetMachineTool
{
    use McpToolHelper;

    public function __construct(
        private readonly MachineRepository $machines,
    ) {}

    public function __invoke(string $machineId): CallToolResult
    {
        $machine = $this->machines->find($machineId);

        if (!$machine) {
            $this->mcpError('not_found', "Machine not found: {$machineId}");
        }

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

        $site = null;
        if ($machine->getSite()) {
            $site = [
                'id'   => $machine->getSite()->getId(),
                'name' => $machine->getSite()->getName(),
            ];
        }

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