"use server";

import { NextResponse } from "next/server";
import { isConvexEnabled } from "@/lib/convex/enabled";
import { getConvexAuthedHttpClient } from "@/lib/convex/server";
import { api } from "@/lib/convex/api";

export async function GET(request: Request) {
  const url = new URL(request.url);
  const gridKey = url.searchParams.get("gridKey");

  if (!gridKey) {
    return NextResponse.json({ code: 400, msg: "gridKey 参数缺失" }, { status: 400 });
  }

  // Convex 模式
  if (isConvexEnabled()) {
    try {
      const client = await getConvexAuthedHttpClient();
      const result = await client.query(api.tables.getByGridKey, { gridKey });

      if (!result) {
        return NextResponse.json({ code: 404, msg: "未查询到相关数据" }, { status: 404 });
      }

      return NextResponse.json({
        code: 200,
        msg: "ok",
        data: result,
      });
    } catch (error) {
      console.error("Convex API error:", error);
      return NextResponse.json({ code: 500, msg: "服务器错误" }, { status: 500 });
    }
  }

  // Supabase 模式
  return NextResponse.json({ code: 501, msg: "当前仅支持 Convex 模式" }, { status: 501 });

  /*
  const supabase = await createSupabaseRouteClient();
  const { data, error } = await supabase
    .from("document_tables")
    .select("id,title,grid_key")
    .eq("grid_key", gridKey)
    .single();

  if (error || !data) {
    return NextResponse.json({ code: 404, msg: "未查询到相关数据" }, { status: 404 });
  }

  return NextResponse.json({
    code: 200,
    msg: "ok",
    data: {
      title: data.title ?? "未命名工作簿",
      lang: "zh",
      gridKey: data.grid_key,
    },
  });
  */
}
