import { NextResponse } from "next/server"
import { prisma } from "@/app/lib/prisma"

const FALLBACK_API_KEY = process.env.DIFY_API_KEY || 'app-lbe2lglt7taGtZk0dG7pAhbx'
const FALLBACK_API_URL = process.env.DIFY_API_URL || 'http://host.docker.internal/v1/chat-messages'

export async function POST(request: Request) {
  try {
    const body = await request.json()
    const { agentId, ...difyBody } = body

    let apiKey = FALLBACK_API_KEY
    let apiUrl = FALLBACK_API_URL

    if (agentId) {
      const agent = await prisma.agent.findUnique({
        where: { id: parseInt(agentId) },
      })
      if (agent?.difyApiUrl && agent?.difyApiKey) {
        apiUrl = agent.difyApiUrl.replace(/\/+$/, '') + '/chat-messages'
        apiKey = agent.difyApiKey
      }
    }

    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ ...difyBody, response_mode: 'streaming' }),
    })

    if (!response.ok) {
      const text = await response.text()
      console.error('Dify API error:', response.status, text.slice(0, 500))
      return NextResponse.json(
        { error: 'Dify request failed' },
        { status: 502 }
      )
    }

    const headers = new Headers()
    headers.set('Content-Type', 'text/event-stream')
    headers.set('Cache-Control', 'no-cache')
    headers.set('Connection', 'keep-alive')

    return new Response(response.body, { headers })
  } catch (error) {
    console.error('Chat API error:', error)
    return NextResponse.json(
      { error: 'Failed to connect to chat service' },
      { status: 500 }
    )
  }
}
