/**
 * Barcode/QR Code Generator Utility
 * Generates barcode and QR code images for inventory items
 */

// Import QR code library
const QRCode = require('qrcode');
// Import fs for file operations
const fs = require('fs');
// Import path for path operations
const path = require('path');
// Import app configuration
const appConfig = require('../config/app');

/**
 * Generate QR code data URL
 * Generates a QR code image as data URL (base64)
 * @param {string} data - Data to encode in QR code (UID or barcode)
 * @param {Object} options - QR code options (optional)
 * @returns {Promise<string>} QR code data URL
 */
const generateQRCodeDataURL = async (data, options = {}) => {
  // Default QR code options
  const qrOptions = {
    errorCorrectionLevel: 'M', // Error correction level (L, M, Q, H)
    type: 'image/png', // Image type
    quality: 0.92, // Image quality
    margin: 1, // Margin around QR code
    color: {
      dark: '#000000', // Dark color (QR code dots)
      light: '#FFFFFF', // Light color (background)
    },
    width: options.width || 200, // QR code width (default: 200)
    ...options, // Merge with provided options
  };
  
  try {
    // Generate QR code as data URL
    const dataURL = await QRCode.toDataURL(data, qrOptions); // Generate QR code
    
    // Return data URL
    return dataURL; // Return data URL
  } catch (error) {
    // Log error
    console.error('QR code generation error:', error); // Log error
    
    // Throw error
    throw new Error(`Failed to generate QR code: ${error.message}`); // Throw error
  }
};

/**
 * Generate QR code file
 * Generates a QR code image file and saves it to disk
 * @param {string} data - Data to encode in QR code (UID or barcode)
 * @param {string} filePath - File path to save QR code image
 * @param {Object} options - QR code options (optional)
 * @returns {Promise<string>} File path where QR code was saved
 */
const generateQRCodeFile = async (data, filePath, options = {}) => {
  // Default QR code options
  const qrOptions = {
    errorCorrectionLevel: 'M', // Error correction level
    type: 'png', // Image type
    quality: 0.92, // Image quality
    margin: 1, // Margin around QR code
    color: {
      dark: '#000000', // Dark color
      light: '#FFFFFF', // Light color
    },
    width: options.width || 200, // QR code width
    ...options, // Merge with provided options
  };
  
  try {
    // Ensure directory exists
    const dir = path.dirname(filePath); // Get directory path
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true }); // Create directory if it doesn't exist
    }
    
    // Generate QR code file
    await QRCode.toFile(filePath, data, qrOptions); // Generate and save QR code
    
    // Return file path
    return filePath; // Return file path
  } catch (error) {
    // Log error
    console.error('QR code file generation error:', error); // Log error
    
    // Throw error
    throw new Error(`Failed to generate QR code file: ${error.message}`); // Throw error
  }
};

/**
 * Generate QR code buffer
 * Generates a QR code image as buffer
 * @param {string} data - Data to encode in QR code (UID or barcode)
 * @param {Object} options - QR code options (optional)
 * @returns {Promise<Buffer>} QR code buffer
 */
const generateQRCodeBuffer = async (data, options = {}) => {
  // Default QR code options
  const qrOptions = {
    errorCorrectionLevel: 'M', // Error correction level
    type: 'png', // Image type
    quality: 0.92, // Image quality
    margin: 1, // Margin around QR code
    color: {
      dark: '#000000', // Dark color
      light: '#FFFFFF', // Light color
    },
    width: options.width || 200, // QR code width
    ...options, // Merge with provided options
  };
  
  try {
    // Generate QR code as buffer
    const buffer = await QRCode.toBuffer(data, qrOptions); // Generate QR code buffer
    
    // Return buffer
    return buffer; // Return buffer
  } catch (error) {
    // Log error
    console.error('QR code buffer generation error:', error); // Log error
    
    // Throw error
    throw new Error(`Failed to generate QR code buffer: ${error.message}`); // Throw error
  }
};

// Export utility functions
module.exports = {
  generateQRCodeDataURL, // Generate QR code data URL function
  generateQRCodeFile, // Generate QR code file function
  generateQRCodeBuffer, // Generate QR code buffer function
};

