import { headers } from "next/headers";
import { auth } from "./auth";

/**
 * 当前登录用户上下文。
 * 由 Auth.js session 提供。
 */

export interface CurrentUser {
  id: bigint;
  nickname: string;
  avatar?: string | null;
  isAnonymous: boolean;
}

export async function getCurrentUser(): Promise<CurrentUser | null> {
  const session = await auth();
  if (!session?.user) return null;

  // session.user.id 由 auth.ts callbacks 注入
  const idStr = (session.user as { id?: string }).id;
  if (!idStr) return null;

  try {
    return {
      id: BigInt(idStr),
      nickname: session.user.name ?? "粉丝",
      avatar: session.user.image,
      isAnonymous: false,
    };
  } catch {
    return null;
  }
}

/**
 * 从 headers 中安全获取真实 IP（火山 CDN/网关回源时透传 X-Forwarded-For）。
 */
export async function getClientIp(): Promise<string | null> {
  const h = await headers();
  const xff = h.get("x-forwarded-for");
  if (xff) return xff.split(",")[0]!.trim();
  return h.get("x-real-ip") ?? null;
}

export async function getUserAgent(): Promise<string | null> {
  const h = await headers();
  return h.get("user-agent");
}
