import { NextRequest, NextResponse } from "next/server"
import { chatWithAI } from "@/lib/ai"
import { getSessionUser } from "@/lib/auth"

export async function POST(request: NextRequest) {
  try {
    const user = await getSessionUser()
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
    }

    const { message } = await request.json()
    if (!message || typeof message !== "string") {
      return NextResponse.json({ error: "Message is required" }, { status: 400 })
    }

    const sessionCookie = request.cookies.get("session")
    const jwtToken = sessionCookie?.value
    if (!jwtToken) {
      return NextResponse.json({ error: "No session token" }, { status: 401 })
    }

    const response = await chatWithAI(message, jwtToken)
    return NextResponse.json({ response })
  } catch (error: any) {
    console.error("AI chat error:", error)
    return NextResponse.json({ error: error.message || "AI service error" }, { status: 500 })
  }
}
