/**
 * POST /api/connectors/tool-test
 *
 * Dry-run a connector tool with user-supplied input and return the raw
 * result. Used by the Schedule create modal's connector_tool form so
 * users can validate parameters before saving the schedule.
 *
 * No dedup, no items_path massaging, no Job preview semantics — that's
 * /api/jobs/preview. This endpoint is the minimal "did the tool call
 * work?" probe.
 *
 * Request body:
 *   {
 *     plugin_id: string,    // e.g. "gitlab"
 *     tool: string,         // e.g. "me"
 *     input?: object        // tool input args
 *   }
 *
 * Response:
 *   {
 *     ok: boolean,
 *     is_error: boolean,
 *     content: string,       // raw tool output (truncated to 8KB)
 *     duration_ms: number,
 *     content_full_size: number,
 *     error?: string         // only when dispatch itself threw
 *   }
 */

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

const MAX_PREVIEW = 8192;

export async function POST(req: Request) {
  let body: any;
  try { body = await req.json(); }
  catch { return NextResponse.json({ ok: false, error: 'invalid JSON body' }, { status: 400 }); }

  const { plugin_id, tool, input } = body || {};
  if (!plugin_id || !tool) {
    return NextResponse.json({ ok: false, error: 'plugin_id and tool are required' }, { status: 400 });
  }

  const callName = `${plugin_id}.${tool}`;
  const t0 = Date.now();
  try {
    const result = await dispatchTool(
      { id: `tool-test-${Date.now()}`, name: callName, input: input || {} },
      { noTruncation: true },
    );
    const content = typeof result.content === 'string' ? result.content : JSON.stringify(result.content ?? '');
    return NextResponse.json({
      ok: !result.is_error,
      is_error: !!result.is_error,
      content: content.length > MAX_PREVIEW ? content.slice(0, MAX_PREVIEW) + '…' : content,
      content_full_size: content.length,
      duration_ms: Date.now() - t0,
    });
  } catch (e) {
    return NextResponse.json({
      ok: false,
      is_error: true,
      content: '',
      content_full_size: 0,
      duration_ms: Date.now() - t0,
      error: (e as Error)?.message || String(e),
    });
  }
}
