import { NextRequest, NextResponse } from "next/server"

/**
 * POST /api/agents/create
 * 
 * Receives agent packages from the client and registers them with n8n.
 * The system prompt is forwarded to an n8n workflow that can store and manage custom agents.
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json() as {
      agentId?: string
      systemPrompt?: string
      metadata?: {
        displayName?: string
        summary?: string
        tags?: string[]
        recommendedIcon?: string
        whenToUse?: string
      }
    }
    const { agentId, systemPrompt, metadata } = body

    // Validate required fields
    if (!agentId || !systemPrompt) {
      return NextResponse.json(
        { error: "Missing required fields: agentId, systemPrompt" },
        { status: 400 }
      )
    }

    // Get the custom agent registration webhook from environment
    const registrationWebhook = process.env.CUSTOM_AGENT_REGISTRATION_WEBHOOK

    if (!registrationWebhook) {
      // If no registration webhook configured, store locally only
      return NextResponse.json({
        success: true,
        agentId,
        message: "Agent stored locally (no registration webhook configured)",
      })
    }

    // Forward to n8n workflow for persistent storage
    const n8nResponse = await fetch(registrationWebhook, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        agentId,
        systemPrompt,
        metadata: {
          displayName: metadata?.displayName,
          summary: metadata?.summary,
          tags: metadata?.tags,
          recommendedIcon: metadata?.recommendedIcon,
          whenToUse: metadata?.whenToUse,
          createdAt: new Date().toISOString(),
        },
      }),
    })

    if (!n8nResponse.ok) {
      const errorText = await n8nResponse.text()
      console.error("n8n registration failed:", errorText)
      
      return NextResponse.json(
        { 
          error: "Failed to register agent with backend",
          details: errorText 
        },
        { status: 500 }
      )
    }

    const result = await n8nResponse.json() as { promptToken?: string }

    return NextResponse.json({
      success: true,
      agentId,
      promptToken: result.promptToken || agentId, // Backend can return a token
      message: "Agent registered successfully",
    })

  } catch (error) {
    console.error("Error creating agent:", error)
    return NextResponse.json(
      { 
        error: "Failed to create agent",
        details: error instanceof Error ? error.message : "Unknown error"
      },
      { status: 500 }
    )
  }
}

