/**
 * QR Code Generator with UTM Tracking
 * 
 * Generates QR codes for hostel outreach campaigns that link to
 * /worker/signup with UTM parameters for attribution tracking.
 */

import QRCode from 'qrcode';

export interface QRCampaignParams {
  hostel_name: string;
  city: string;
  batch_id: string;
}

export interface QRCodeOptions {
  /** Width/height in pixels (default: 400 for print quality) */
  size?: number;
  /** Error correction level (default: 'H' for high — handles damage/dirt) */
  errorCorrectionLevel?: 'L' | 'M' | 'Q' | 'H';
  /** Margin in modules (default: 2) */
  margin?: number;
  /** Dark module colour (default: '#000000') */
  darkColor?: string;
  /** Light module colour (default: '#FFFFFF') */
  lightColor?: string;
}

const BASE_URL = 'https://rateright.com.au';
const SIGNUP_PATH = '/worker/signup';

/**
 * Build a UTM-tracked signup URL from campaign parameters.
 */
export function buildSignupUrl(params: QRCampaignParams): string {
  const slug = params.hostel_name
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-|-$/g, '');

  const url = new URL(SIGNUP_PATH, BASE_URL);
  url.searchParams.set('utm_source', 'hostel');
  url.searchParams.set('utm_medium', 'poster');
  url.searchParams.set('utm_campaign', `hostel-${params.batch_id}`);
  url.searchParams.set('utm_content', slug);
  url.searchParams.set('utm_term', params.city.toLowerCase().replace(/\s+/g, '-'));

  return url.toString();
}

/**
 * Generate a QR code as a PNG buffer.
 */
export async function generateQRCodeBuffer(
  params: QRCampaignParams,
  options: QRCodeOptions = {}
): Promise<Buffer> {
  const url = buildSignupUrl(params);
  const {
    size = 400,
    errorCorrectionLevel = 'H',
    margin = 2,
    darkColor = '#000000',
    lightColor = '#FFFFFF',
  } = options;

  const buffer = await QRCode.toBuffer(url, {
    type: 'png',
    width: size,
    errorCorrectionLevel,
    margin,
    color: {
      dark: darkColor,
      light: lightColor,
    },
  });

  return buffer;
}

/**
 * Generate a QR code as a data URL (for embedding in HTML/emails).
 */
export async function generateQRCodeDataUrl(
  params: QRCampaignParams,
  options: QRCodeOptions = {}
): Promise<string> {
  const url = buildSignupUrl(params);
  const {
    size = 400,
    errorCorrectionLevel = 'H',
    margin = 2,
    darkColor = '#000000',
    lightColor = '#FFFFFF',
  } = options;

  return QRCode.toDataURL(url, {
    width: size,
    errorCorrectionLevel,
    margin,
    color: {
      dark: darkColor,
      light: lightColor,
    },
  });
}
