/**
 * 设备指纹模块
 *
 * 安全说明：设备指纹存储在内存中，不写入 localStorage/sessionStorage
 * 以防止 XSS 攻击者读取或注入恶意设备指纹
 */

export interface DeviceFingerprint {
  device_id: string
  device_name: string
  device_browser: string
  device_os: string
}

// 内存中的设备指纹缓存
let cachedFingerprint: DeviceFingerprint | null = null

// 从 User-Agent 解析浏览器信息
function parseBrowser(ua: string): string {
  if (ua.includes('Chrome')) return 'Chrome'
  if (ua.includes('Firefox')) return 'Firefox'
  if (ua.includes('Safari')) return 'Safari'
  if (ua.includes('Edge')) return 'Edge'
  if (ua.includes('Opera')) return 'Opera'
  if (ua.includes('IE')) return 'IE'
  return 'Unknown'
}

// 从 User-Agent 解析操作系统信息
function parseOS(ua: string): string {
  if (ua.includes('Windows')) return 'Windows'
  if (ua.includes('Mac OS') || ua.includes('macOS')) return 'macOS'
  if (ua.includes('Linux')) return 'Linux'
  if (ua.includes('Android')) return 'Android'
  if (ua.includes('iOS') || ua.includes('iPhone') || ua.includes('iPad')) return 'iOS'
  return 'Unknown'
}

// 生成设备 ID
function generateDeviceId(): string {
  if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
    return crypto.randomUUID()
  }
  // Fallback: 使用随机字符串（不如 UUID 安全但可用）
  const browser = parseBrowser(navigator.userAgent)
  const os = parseOS(navigator.userAgent)
  return `${browser}-${os}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
}

/**
 * 获取设备指纹
 * 每次调用返回相同的内存缓存实例（单例模式）
 */
export function getDeviceFingerprint(): DeviceFingerprint {
  if (cachedFingerprint) {
    return cachedFingerprint
  }

  const ua = navigator.userAgent
  const browser = parseBrowser(ua)
  const os = parseOS(ua)

  cachedFingerprint = {
    device_id: generateDeviceId(),
    device_name: `${browser} on ${os}`,
    device_browser: browser,
    device_os: os,
  }

  return cachedFingerprint
}

/**
 * 清除缓存的设备指纹（用于测试或登出）
 */
export function clearDeviceFingerprint(): void {
  cachedFingerprint = null
}
