/**
 * POST /api/agent/[runId]/command - Send manual command
 */

import { NextRequest, NextResponse } from "next/server"
import { getCloudflareContext } from "@opennextjs/cloudflare"

function getDurableObjectStub(runId: string, env: any) {
  const id = env.BANDIT_AGENT.idFromName(runId)
  return env.BANDIT_AGENT.get(id)
}

export async function POST(
  request: NextRequest,
  { params }: { params: { runId: string } }
) {
  const runId = params.runId
  const body = await request.json()
  const { env } = await getCloudflareContext()

  if (!env?.BANDIT_AGENT) {
    return NextResponse.json(
      { error: "Durable Object binding not found" },
      { status: 500 }
    )
  }

  try {
    const stub = getDurableObjectStub(runId, env)
    const response = await stub.fetch(`http://do/command`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    })
    const data = await response.json()
    return NextResponse.json(data, { status: response.status })
  } catch (error) {
    console.error('Agent command error:', error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Unknown error' },
      { status: 500 }
    )
  }
}


