import { resolve } from "path";
import type { Canvas } from "skia-canvas";
import { getLogoNames } from "../utils/logos";

const normalize = (s: string) => s.toLowerCase().replace(/[\s_-]+/g, "");

export default defineEventHandler(async (event) => {
  const { format, logo, content } = await getValidatedQuery(
    event,
    settingsSchema.parse,
  );

  let canvas: Canvas;

  if (logo) {
    const names = await getLogoNames();
    if (!names)
      throw createError({
        statusCode: 500,
        message: "Could not retrieve logos",
      });

    const match = names.find((n) => normalize(n) === normalize(logo));
    const resolvedLogo = match ?? logo;

    canvas = await renderQRCodeToCanvas(
      content,
      resolve("public", `logos/${resolvedLogo}.png`),
    );
  } else {
    canvas = await renderQRCodeToCanvas(content, undefined);
  }

  const image = canvas.toBuffer(format);
  event.node.res.setHeader("Content-Type", `image/${format}`);
  event.node.res.setHeader(
    "Content-Disposition",
    `filename="qrcode.${format}"`,
  );
  return image;
});
