"use server";

import { NextResponse } from "next/server";
import { createDefaultTableSnapshot } from "@/lib/online-table";
import type { DocumentTableSnapshot, TableSchema } from "@/types/online-table";
import { isConvexEnabled } from "@/lib/convex/enabled";
import { getConvexAuthedHttpClient } from "@/lib/convex/server";
import { api } from "@/lib/convex/api";

const fallbackSchema: TableSchema = {
  columns: [],
  frozenRowCount: 0,
  frozenColCount: 0,
};

export async function POST(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 tableData = await client.query(api.tables.getByGridKeyFull, { gridKey });

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

      const snapshot = (tableData.snapshot as DocumentTableSnapshot | null) ?? null;
      const schema = (tableData.schema as TableSchema | null) ?? fallbackSchema;

      let payload: unknown[] = [];
      if (snapshot?.luckysheet && Array.isArray(snapshot.luckysheet)) {
        payload = snapshot.luckysheet;
      } else {
        const defaultSnapshot = createDefaultTableSnapshot(schema);
        payload = defaultSnapshot.luckysheet ?? [];
      }

      const body = JSON.stringify(payload);
      return new NextResponse(body, {
        headers: { "Content-Type": "text/plain; charset=utf-8" },
      });
    } catch (error) {
      console.error("Convex API error:", error);
      return NextResponse.json({ code: 500, msg: "服务器错误" }, { status: 500 });
    }
  }

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

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

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

  const snapshot = (data.snapshot as DocumentTableSnapshot | null) ?? null;
  const schema = (data.schema as TableSchema | null) ?? fallbackSchema;

  let payload: unknown[] = [];
  if (snapshot?.luckysheet && Array.isArray(snapshot.luckysheet)) {
    payload = snapshot.luckysheet;
  } else {
    const defaultSnapshot = createDefaultTableSnapshot(schema);
    payload = defaultSnapshot.luckysheet ?? [];
  }

  const body = JSON.stringify(payload);
  return new NextResponse(body, {
    headers: { "Content-Type": "text/plain; charset=utf-8" },
  });
  */
}
