const DEVICE_HASH_SALT = 0x5a_3c_7e_9b;

/**
 * Encode device id (user_device.id) to 8-char hex hash (bidirectional)
 * e.g. 1 → "5A3C7E9A", 42 → "5A3C7EA1"
 */
export function deviceIdToHash(id: number): string {
  // biome-ignore lint/suspicious/noBitwiseOperators: intentional XOR hash
  return ((id ^ DEVICE_HASH_SALT) >>> 0)
    .toString(16)
    .toUpperCase()
    .padStart(8, "0");
}

/**
 * Decode 8-char hex hash back to device id
 * e.g. "5A3C7E9A" → 1
 */
export function hashToDeviceId(hash: string): number {
  // biome-ignore lint/suspicious/noBitwiseOperators: intentional XOR hash
  return (Number.parseInt(hash, 16) ^ DEVICE_HASH_SALT) >>> 0;
}

/**
 * Shorten a long device identifier (e.g. "device68c71ab9f82d...") to 8-char display
 * Used when only the identifier string is available (no numeric device id)
 */
export function shortenDeviceIdentifier(identifier: string): string {
  return identifier
    .replace(/^device/i, "")
    .slice(0, 8)
    .toUpperCase();
}

/**
 * 从 User-Agent 字符串解析设备平台类型
 * 与后端 parseDeviceType 逻辑保持一致
 * @param userAgent - 设备的 User-Agent 字符串
 * @returns 设备平台类型字符串，如 "iPhone"、"Android" 等，未识别时返回空字符串
 */
export function parseDeviceType(userAgent: string): string {
  if (!userAgent) return "";
  const ua = userAgent.toLowerCase();
  if (ua.includes("iphone")) return "iPhone";
  if (ua.includes("ipad")) return "iPad";
  if (ua.includes("android")) return "Android";
  if (ua.includes("windows")) return "Windows";
  if (ua.includes("macintosh") || ua.includes("mac os")) return "Mac";
  if (ua.includes("linux")) return "Linux";
  return "";
}
