/// <reference types="@fastly/js-compute" />

import qrcode from 'qrcode-generator';

addEventListener('fetch', (event) => event.respondWith(handleRequest(event)));

function base64ToArrayBuffer(data) {
  const raw = atob(data);
  const rawLength = raw.length;
  const array = new ArrayBuffer(rawLength);
  const view = new Uint8Array(array);
  for (let i = 0; i < rawLength; i++) {
    view[i] = raw.charCodeAt(i);
  }
  return array;
}

async function handleRequest(event) {

  // Require HEAD or GET
  if (event.request.method !== 'HEAD' && event.request.method !== 'GET') {
    return new Response(null, {
      status: 405, // method not supported
    });
  }

  const url = new URL(event.request.url);

  // Require q= param, which will be used as source string
  const q = url.searchParams.get('q');
  if (q == null || q === '') {
    return new Response('Parameter q required', {
      status: 400, // bad request
    });
  }

  // Constructor takes QR code type number (0 = auto)
  // and error correction level (L = low resilience)
  const qr = qrcode(0, 'L');

  // Add the string and build the QR code data
  qr.addData(q);
  qr.make();

  // Build a GIF image and returns it as a data url
  const qrCodeDataUrl = qr.createDataURL();

  // Strip data url preamble and convert body to binary
  const qrCodeBase64 = qrCodeDataUrl.slice('data:image/gif;base64,'.length);
  const qrCodeArrayBuffer = base64ToArrayBuffer(qrCodeBase64);

  return new Response(
    qrCodeArrayBuffer,
    {
      status: 200,
      headers: {
        'content-type': 'image/gif',
      },
    },
  );
}