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

interface RecentPayload {
  workspaceId: string;
  documentId: string;
}

export async function POST(request: Request) {
  if (isConvexEnabled()) {
    const { auth, client } = await getAuthedConvexClient();
    const { workspaceId, documentId }: RecentPayload = await request.json();

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

    await client.mutation(api.recents.upsert, {
      userId: auth.userId,
      workspaceId,
      documentId,
      lastAccessedAt: new Date().toISOString(),
    });

    return NextResponse.json({ ok: true });
  }

  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 { workspaceId, documentId }: RecentPayload = await request.json();

  if (!workspaceId || !documentId) {
    return NextResponse.json({ error: "缺少参数" }, { 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 { error } = await supabase.from("user_recent_pages").upsert(
    {
      user_id: session.user.id,
      workspace_id: workspaceId,
      document_id: documentId,
      last_accessed_at: new Date().toISOString(),
    },
    { onConflict: "user_id,document_id" },
  );

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

  return NextResponse.json({ ok: true });
  */
}
