import { NextResponse } from 'next/server'
import { oapiClient } from '../oapi-client'
import { getDefaultAgentId, getDefaultAgentName } from '../nova-config'
import { getProjectId, getUserId } from '@/utils/getAuth'

const buildWssUrl = () => {
  const baseUrl = process.env.NOVA_BASE_URL!
  const wssBase = baseUrl.replace('https://', 'wss://').replace('http://', 'ws://')
  const authorization = process.env.NOVA_ACCESS_KEY
  const tenantId = process.env.NOVA_TENANT_ID
  return `${wssBase}/v1/super_agent/chat/completions?Authorization=${authorization}&X-Locale=zh&X-Region=CN&Tenant-Id=${tenantId}`
}

export async function GET() {
  const agentId = getDefaultAgentId()
  const agentName = getDefaultAgentName()
  
  const list = await oapiClient.get('/v1/oapi/super_agent/chat/conversation_list', {
    page_no: 1,
    page_size: 10,
    agent_id: agentId,
  })

  const conversationId = list.data?.[0]?.conversation_id

  if (!conversationId) {
    const res = await oapiClient.post('/v1/oapi/super_agent/chat/create_conversation', {
      agent_id: agentId,
      title: 'new conversation',
      conversation_type: 'REACTUS',
      external_app_id: getProjectId(),
      external_user_id: getUserId(),
    })

    return NextResponse.json(
      {
        code: 0,
        message: 'ok',
        data: {
          apiBaseUrl: '/api',
          agent_id: agentId,
          agent_name: agentName,
          conversation_id: res.conversation_id,
          wssUrl: buildWssUrl(),
          token: process.env.NOVA_ACCESS_KEY,
          tenantId: process.env.NOVA_TENANT_ID,
        },
      },
      { status: 200 }
    )
  }

  return NextResponse.json(
    {
      success: true,
      data: {
        apiBaseUrl: '/api',
        agent_id: agentId,
        agent_name: agentName,
        conversation_id: conversationId,
        wssUrl: buildWssUrl(),
        token: process.env.NOVA_ACCESS_KEY,
        tenantId: process.env.NOVA_TENANT_ID,
      },
    },
    { status: 200 }
  )
}
