import QRCode from 'qrcode'

export interface QRCodeOptions {
  width?: number
  margin?: number
  color?: {
    dark?: string
    light?: string
  }
}

/**
 * Generate a QR code as a data URL
 * @param text - The text/data to encode in the QR code
 * @param options - Optional configuration for QR code generation
 * @returns Promise<string> - Data URL of the QR code image
 */
export async function generateQRCode(
  text: string,
  options: QRCodeOptions = {}
): Promise<string> {
  const {
    width = 300,
    margin = 2,
    color = {
      dark: '#000000',
      light: '#ffffff'
    }
  } = options

  try {
    const dataUrl = await QRCode.toDataURL(text, {
      width,
      margin,
      color,
      errorCorrectionLevel: 'M' // Medium error correction
    })
    return dataUrl
  } catch (error) {
    console.error('Error generating QR code:', error)
    throw new Error('Failed to generate QR code')
  }
}

/**
 * Generate a QR code as a base64 string (without the data URL prefix)
 * @param text - The text/data to encode in the QR code
 * @param options - Optional configuration for QR code generation
 * @returns Promise<string> - Base64 string of the QR code image
 */
export async function generateQRCodeBase64(
  text: string,
  options: QRCodeOptions = {}
): Promise<string> {
  const dataUrl = await generateQRCode(text, options)
  // Remove the "data:image/png;base64," prefix
  return dataUrl.split(',')[1]
}

/**
 * Generate a QR code for a product label
 * @param productRef - Product reference/ID
 * @param productName - Product name/designation
 * @returns Promise<string> - Data URL of the QR code image
 */
export async function generateProductQRCode(
  productRef: string,
  productName?: string
): Promise<string> {
  const text = productName
    ? `PROD:${productRef}|${productName}`
    : `PROD:${productRef}`

  return generateQRCode(text, {
    width: 200,
    margin: 1,
    color: {
      dark: '#000000',
      light: '#ffffff'
    }
  })
}
