import { type NextRequest, NextResponse } from "next/server"
import { getIntelligentSearchService } from "@/services/intelligent-search-service"
import { getMindsDBConnector } from "@/lib/mindsdb-connector"

// 初始化MindsDB连接
const mindsDBConfig = {
  host: process.env.MINDSDB_HOST || "localhost",
  port: Number.parseInt(process.env.MINDSDB_PORT || "47334"),
  username: process.env.MINDSDB_USERNAME || "mindsdb",
  password: process.env.MINDSDB_PASSWORD || "",
  database: process.env.MINDSDB_DATABASE || "mindsdb",
}

// 初始化连接器
getMindsDBConnector(mindsDBConfig)

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const query = searchParams.get("q") || ""
    const type = (searchParams.get("type") as "user" | "traffic" | "all") || "all"
    const limit = Number.parseInt(searchParams.get("limit") || "50")
    const offset = Number.parseInt(searchParams.get("offset") || "0")
    const useAI = searchParams.get("ai") === "true"
    const includeInsights = searchParams.get("insights") === "true"

    if (!query.trim()) {
      return NextResponse.json({ error: "搜索查询不能为空" }, { status: 400 })
    }

    const searchService = getIntelligentSearchService()

    const results = await searchService.search(query, type, {
      limit,
      offset,
      useAI,
      includeInsights,
      filters: {},
    })

    return NextResponse.json(results)
  } catch (error) {
    console.error("搜索API错误:", error)
    return NextResponse.json({ error: "搜索失败，请稍后重试" }, { status: 500 })
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { query, type = "all", options = {} } = body

    if (!query || !query.trim()) {
      return NextResponse.json({ error: "搜索查询不能为空" }, { status: 400 })
    }

    const searchService = getIntelligentSearchService()
    const results = await searchService.search(query, type, options)

    return NextResponse.json(results)
  } catch (error) {
    console.error("搜索API错误:", error)
    return NextResponse.json({ error: "搜索失败，请稍后重试" }, { status: 500 })
  }
}
