import { ConvexHttpClient } from "convex/browser";
import { convexAuthNextjsToken } from "@convex-dev/auth/nextjs/server";
import { isDevAuthEnabled } from "@/lib/auth/devUser";

let cached: ConvexHttpClient | null = null;

export function getConvexHttpClient(): ConvexHttpClient {
  if (cached) return cached;

  const url = process.env.CONVEX_SELF_HOSTED_URL ?? process.env.NEXT_PUBLIC_CONVEX_URL;
  if (!url) {
    throw new Error("缺少 CONVEX_SELF_HOSTED_URL / NEXT_PUBLIC_CONVEX_URL 配置");
  }

  const client = new ConvexHttpClient(url);
  const adminKey = process.env.CONVEX_SELF_HOSTED_ADMIN_KEY;
  if (adminKey) {
    // 说明：ConvexHttpClient 的类型声明可能未暴露 setAdminAuth（但运行期存在）。
    // 这里用最小侵入方式兼容自托管管理密钥。
    (client as any).setAdminAuth(adminKey);
  }

  cached = client;
  return client;
}

export async function getConvexAuthedHttpClient(): Promise<ConvexHttpClient> {
  const url = process.env.CONVEX_SELF_HOSTED_URL ?? process.env.NEXT_PUBLIC_CONVEX_URL;
  if (!url) {
    throw new Error("缺少 CONVEX_SELF_HOSTED_URL / NEXT_PUBLIC_CONVEX_URL 配置");
  }

  const token = await convexAuthNextjsToken();
  if (!token) {
    // 说明：开发用户模式（MNOTE_DEV_AUTH=1）用于迁移/联调阶段的“免登录”体验。
    // 此时浏览器侧可能没有 Convex Auth cookies，但服务端仍需要能访问 Convex。
    // 若配置了自托管 Admin Key，则允许在开发用户模式下回退到 Admin Auth（仅本地/联调使用）。
    const adminKey = process.env.CONVEX_SELF_HOSTED_ADMIN_KEY;
    if (adminKey && isDevAuthEnabled()) {
      const client = new ConvexHttpClient(url);
      (client as any).setAdminAuth(adminKey);
      return client;
    }

    throw new Error("未登录");
  }

  const client = new ConvexHttpClient(url);
  // 说明：ConvexHttpClient 的类型声明可能未暴露 setAuth（但运行期存在）。
  // 这里用最小侵入方式兼容 Convex Auth token。
  (client as any).setAuth(token);
  return client;
}
