/**
 * QR PNG generation and R2 upload helpers.
 *
 * Uses the `qrcode` npm package (already installed).
 * Generated PNGs are 512×512, error correction M, margin 2.
 */

import QRCode from 'qrcode';
import { putObject } from './r2.js';

/**
 * Generates a QR code PNG for the given data string.
 *
 * @param data - The payload to encode (e.g. a signed QR token URL).
 * @returns    The raw PNG bytes as a Uint8Array.
 */
export async function generateQrPng(data: string): Promise<Uint8Array> {
  const buffer = await QRCode.toBuffer(data, {
    type: 'png',
    width: 512,
    errorCorrectionLevel: 'M',
    margin: 2,
  });
  return new Uint8Array(buffer);
}

/**
 * Generates a QR PNG for a purchase token, uploads it to private R2, and returns
 * an authenticated image endpoint.
 *
 * R2 key: `qr/{purchaseId}.png`
 * URL: `{publicBase}/api/purchases/{purchaseId}/qr/image`
 *
 * @param bucket     - Bound R2Bucket from the Worker env.
 * @param purchaseId - The purchase UUID.
 * @param token      - The HMAC-signed QR token payload (embedded in the QR).
 * @param publicBase - Base URL of the public R2 / CDN endpoint (no trailing slash).
 * @returns          The authenticated URL of the uploaded QR PNG.
 */
export async function uploadPurchaseQr(
  bucket: R2Bucket,
  purchaseId: string,
  token: string,
  publicBase: string,
): Promise<string> {
  const pngBytes = await generateQrPng(token);
  const key = `qr/${purchaseId}.png`;

  await putObject(bucket, key, pngBytes.buffer as ArrayBuffer, {
    contentType: 'image/png',
    cacheControl: 'public, max-age=31536000, immutable',
  });

  return `${publicBase}/api/purchases/${purchaseId}/qr/image`;
}
