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

// 定义请求体类型
interface CreateTableRequestBody {
  documentId: string;
  title: string;
  schema: TableSchema;
  snapshot?: DocumentTableSnapshot | null;
}

export async function POST(request: Request) {
  // Convex 模式
  if (isConvexEnabled()) {
    const { auth, client } = await getAuthedConvexClient();

    try {
      const { documentId, title, schema, snapshot } = await request.json() as CreateTableRequestBody;

      if (!documentId || !title || !schema) {
        return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
      }

      // 获取 document 所在的 workspace_id
      const document = await client.query(api.documents.getMeta, {
        id: documentId,
      });

      if (!document) {
        return NextResponse.json({ error: "Document not found" }, { status: 404 });
      }

      // 创建表格
      const result = await client.mutation(api.tables.create, {
        userId: auth.userId,
        workspaceId: document.workspace_id,
        documentId,
        title,
        schema,
        snapshot,
      });

      return NextResponse.json(result, { status: 201 });

    } catch (error) {
      console.error("Convex API error:", error);
      return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
    }
  }

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

  /*
  const supabase = await createSupabaseRouteClient();

  const { data: { user } } = await supabase.auth.getUser();

  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const { documentId, title, schema, snapshot } = await request.json() as CreateTableRequestBody;

    if (!documentId || !title || !schema) {
      return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
    }

    // 1. 获取 document 所在的 workspace_id
    const { data: documentData, error: documentError } = await supabase
      .from("documents")
      .select("workspace_id")
      .eq("id", documentId)
      .single();

    if (documentError || !documentData?.workspace_id) {
      console.error("Error fetching document or workspace:", documentError);
      return NextResponse.json({ error: "Document not found or missing workspace_id" }, { status: 404 });
    }

    const workspaceId = documentData.workspace_id;

    // 2. 插入新的 document_tables 记录
    const { data: newTable, error: insertError } = await supabase
      .from("document_tables")
      .insert({
        workspace_id: workspaceId,
        document_id: documentId,
        title: title,
        schema: schema,
        view_preferences: {},
        is_archived: false,
        created_by: user.id,
        updated_by: user.id,
        snapshot: snapshot ?? {},
      })
      .select()
      .single();

    if (insertError) {
      console.error("Error inserting table:", insertError);
      return NextResponse.json({ error: "Failed to create table in database" }, { status: 500 });
    }

    // 假设 document_tables 返回的结构与 DocumentTable 接口兼容
    return NextResponse.json(newTable, { status: 201 });

  } catch (error) {
    console.error("API error:", error);
    return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
  }
  */
}
