import { headers } from 'next/headers'
import { serverDeviceManager } from '@/lib/auth/server-device'

// 获取服务端的cookie字符串
export async function getServerCookies(): Promise<string> {
  const headersList = await headers()
  return headersList.get('cookie') || ''
}

// 检查服务端是否已登录
export async function isServerAuthenticated(): Promise<boolean> {
  const cookieString = await getServerCookies()
  const { tokenManager } = await import('@/lib/auth/token')
  return tokenManager.isAuthenticated(cookieString)
}

// 获取服务端设备ID（从cookie或header）
export async function getServerDeviceId(): Promise<string | null> {
  // 优先从cookie获取
  const deviceIdFromCookie = await serverDeviceManager.getDeviceId()
  if (deviceIdFromCookie) {
    return deviceIdFromCookie
  }

  // 从header获取（中间件设置的）
  const deviceIdFromHeader = await serverDeviceManager.getDeviceIdFromHeaders()
  return deviceIdFromHeader
}

// 确保有设备ID（但不创建，只返回现有的或null）
export async function ensureServerDeviceId(): Promise<string | null> {
  return await getServerDeviceId()
}
