import { cookies } from 'next/headers';

const authInfoKey = 'auth';

/**
 * 服务端获取 authInfo
 * 从 cookies 中读取，因为服务端无法访问 localStorage
 */
export async function getServerAuthInfo() {
  const cookieStore = await cookies();
  const authInfoStr = cookieStore.get(authInfoKey)?.value;

  if (!authInfoStr) {
    return null;
  }

  try {
    return JSON.parse(authInfoStr);
  } catch {
    return null;
  }
}

/**
 * 服务端获取 token
 * 从 cookies 中读取 authInfo，然后提取 token
 */
export async function getServerToken() {
  const authInfo = await getServerAuthInfo();
  return authInfo?.token || null;
}
