/**
 * 访客预约二维码工具函数
 * 二维码内容：{ id, timestamp, sign }
 * sign = md5(id + "lktx" + timestamp)
 */

import md5 from '@/lib/md5'

const SALT = 'lktx'

/**
 * 生成二维码数据
 */
export function generateQRData(id: number): { id: number; timestamp: number; sign: string } {
  const timestamp = Date.now()
  const sign = md5(id + SALT + timestamp)
  return { id, timestamp, sign }
}

/**
 * 验证二维码数据
 * @returns { valid: boolean, expired: boolean, timeDiff: number }
 */
export function verifyQRData(data: { id: number; timestamp: number; sign: string }): {
  valid: boolean
  expired: boolean
  timeDiff: number
} {
  const now = Date.now()
  const timeDiff = now - data.timestamp
  const expectedSign = md5(data.id + SALT + data.timestamp)

  if (data.sign !== expectedSign) {
    return { valid: false, expired: false, timeDiff }
  }

  return {
    valid: true,
    expired: timeDiff > 10000, // 10秒过期
    timeDiff,
  }
}

/**
 * 格式化二维码生成时间
 */
export function formatQRTime(timestamp: number): string {
  const d = new Date(timestamp)
  const pad = (n: number) => String(n).padStart(2, '0')
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}
