import qrcodeGenerator from '@/lib/vendor/qrcode-generator'

type QrcodeFactory = (typeNumber: number, errorCorrectionLevel: 'L' | 'M' | 'Q' | 'H') => {
  addData: (data: string) => void
  make: () => void
  createDataURL: (cellSize?: number, margin?: number) => string
}

const qrcode = qrcodeGenerator as QrcodeFactory

export function generateQrCodeDataUrl(text: string, options?: { cellSize?: number; margin?: number }) {
  const qr = qrcode(0, 'M')
  qr.addData(text)
  qr.make()
  return qr.createDataURL(options?.cellSize ?? 6, options?.margin ?? 2)
}

/**
 * Normalize a WeChat iLink QR response into a usable image URL. The API may
 * return:
 *  - a data: URL (already usable)
 *  - an http(s)/blob: URL (already usable)
 *  - a protocol-relative URL (e.g. //cdn.example.com/qr.png)
 *  - a raw base64 payload (no data URL prefix) — we add the prefix
 *  - empty / null → empty string
 */
export function normalizeQrCodeUrl(value?: string | null): string {
  if (!value) return ''
  const trimmed = value.trim()
  if (!trimmed) return ''

  if (
    trimmed.startsWith('data:image/') ||
    trimmed.startsWith('http://') ||
    trimmed.startsWith('https://') ||
    trimmed.startsWith('blob:')
  ) {
    return trimmed
  }
  if (trimmed.startsWith('//')) {
    return `https:${trimmed}`
  }
  // Raw base64 — the WeChat QR API sometimes returns this without prefix.
  if (/^[A-Za-z0-9+/=\r\n]+$/.test(trimmed)) {
    return `data:image/png;base64,${trimmed.replace(/\s+/g, '')}`
  }
  return trimmed
}
