/**
 * POST /api/connector-tool
 *
 * Single-tool dispatch for internal callers (pipelines, jobs, CLI). Wraps
 * lib/chat/tool-dispatcher.dispatchTool so http/shell/browser connectors
 * are all callable through one shape:
 *
 *   { "plugin_id": "teams", "tool": "send_message",
 *     "input": { "name": "Alice", "text": "MR ready: https://..." } }
 *
 * Returns the tool_result shape: { content: string, is_error?: boolean }.
 *
 * Loopback-only — middleware skips auth for this path on 127.0.0.1 /
 * localhost; outside-host requests fall back to the normal X-Forge-Token
 * check.
 */

import { NextResponse } from 'next/server';
import { dispatchTool } from '@/lib/chat/tool-dispatcher';

export async function POST(req: Request) {
  let body: any = {};
  try { body = await req.json(); } catch {}
  const pluginId = String(body?.plugin_id || '').trim();
  const tool = String(body?.tool || '').trim();
  if (!pluginId || !tool) {
    return NextResponse.json({ error: 'plugin_id and tool are required' }, { status: 400 });
  }
  const name = `${pluginId}.${tool}`;
  const result = await dispatchTool({
    id: `internal-${Date.now()}`,
    name,
    input: body?.input ?? {},
  });
  // Always 200 — the result carries is_error if the dispatched tool failed.
  // (Network / wiring errors throw inside dispatchTool and bubble as 500.)
  return NextResponse.json(result);
}
