import { getAuthUserId } from "@convex-dev/auth/server";

function readEnv(key: string): string | undefined {
  const raw = process.env[key];
  if (!raw) return undefined;
  const trimmed = raw.trim();
  return trimmed ? trimmed : undefined;
}

function isDevAuthEnabled(): boolean {
  return readEnv("MNOTE_DEV_AUTH") === "1" || readEnv("NEXT_PUBLIC_MNOTE_DEV_AUTH") === "1";
}

export async function requireUserId(ctx: any): Promise<string> {
  const userId = await getAuthUserId(ctx);
  if (userId !== null) {
    return String(userId);
  }

  const devUserId = readEnv("DEV_USER_ID");
  if (isDevAuthEnabled() || devUserId) {
    return devUserId ?? "dev-user";
  }

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