import { NextResponse } from "next/server"
import { getDatabases, getDatabaseStructure, getTableStructure } from "@/lib/db-connector"

export const dynamic = "force-dynamic"

export async function GET(req: Request) {
  try {
    const url = new URL(req.url)
    const database = url.searchParams.get("database")
    const table = url.searchParams.get("table")

    // 无查询参数：返回数据库列表（[{ Database: string }]）
    if (!database) {
      const dbs = await getDatabases()
      return NextResponse.json({ success: true, data: dbs })
    }

    // 有 database + table：返回表结构
    if (database && table) {
      const fields = await getTableStructure(database, table)
      return NextResponse.json({ success: true, data: fields })
    }

    // 仅有 database：返回整个库的结构
    const structure = await getDatabaseStructure(database)
    return NextResponse.json({ success: true, data: structure })
  } catch (error) {
    console.error("数据库结构API错误:", error)
    return NextResponse.json({ success: false, message: "获取数据库结构失败" }, { status: 500 })
  }
}
