import { authenticate } from "../shopify.server";
import prisma from "../db.server";

export async function loader({ request, params }) {
  await authenticate.public.appProxy(request);

  const customization = await prisma.customization.findUnique({
    where: { id: params.id },
  });

  const url = new URL(request.url);
  const type = url.searchParams.get("type");
  const dataUrl = type === "impression"
    ? customization?.imageImpression
    : type === "esquisse"
      ? customization?.imageEsquisse
      : customization?.image2D;
  if (!dataUrl) {
    return new Response("Not found", { status: 404 });
  }

  const match = /^data:(image\/[a-zA-Z+.-]+);base64,(.+)$/.exec(dataUrl);
  if (!match) {
    return new Response("Invalid image data", { status: 422 });
  }

  const [, contentType, base64] = match;
  const bytes = Buffer.from(base64, "base64");

  return new Response(bytes, {
    headers: {
      "Content-Type": contentType,
      "Cache-Control": "public, max-age=31536000, immutable",
    },
  });
}
