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

export async function GET(request: Request) {
  if (isConvexEnabled()) {
    const { auth, client } = await getAuthedConvexClient();
    const { searchParams } = new URL(request.url);
    const workspaceId = searchParams.get("workspaceId");
    const pageId = searchParams.get("pageId");
    if (!workspaceId || !pageId) {
      return NextResponse.json({ error: "缺少 workspaceId 或 pageId" }, { status: 400 });
    }

    const limit = Number(searchParams.get("limit") ?? "50");
    const offset = Number(searchParams.get("offset") ?? "0");

    const backlinks = await client.query(api.references.listBacklinks, {
      userId: auth.userId,
      workspaceId,
      pageId,
      limit: Number.isFinite(limit) ? limit : 50,
      offset: Number.isFinite(offset) ? offset : 0,
    });

    return NextResponse.json({ backlinks });
  }

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

  /*
  const supabase = await createSupabaseRouteClient();
  const {
    data: { session },
  } = await supabase.auth.getSession();

  if (!session) {
    return NextResponse.json({ error: "未登录" }, { status: 401 });
  }

  const { searchParams } = new URL(request.url);
  const workspaceId = searchParams.get("workspaceId");
  const pageId = searchParams.get("pageId");
  const limit = Number(searchParams.get("limit") ?? "50");
  const offset = Number(searchParams.get("offset") ?? "0");

  if (!workspaceId || !pageId) {
    return NextResponse.json({ error: "缺少 workspaceId 或 pageId" }, { status: 400 });
  }

  const { data: membership, error: membershipError } = await supabase
    .from("workspace_members")
    .select("workspace_id")
    .eq("workspace_id", workspaceId)
    .eq("user_id", session.user.id)
    .maybeSingle();

  if (membershipError) {
    return NextResponse.json({ error: membershipError.message }, { status: 500 });
  }
  if (!membership) {
    return NextResponse.json({ error: "无权访问该工作空间" }, { status: 403 });
  }

  const { data, error } = await supabase.rpc("list_backlinks", {
    p_workspace_id: workspaceId,
    p_target_page_id: pageId,
    p_limit: Number.isFinite(limit) ? limit : 50,
    p_offset: Number.isFinite(offset) ? offset : 0,
  });

  if (error) {
    return NextResponse.json({ error: error.message }, { status: 500 });
  }

  return NextResponse.json({ backlinks: data ?? [] });
  */
}
