import { NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import { requireApiAuthWithOrg, handleApiError } from "@/lib/api-auth";
import { getSiteUrlFromRequest } from "@/lib/site-url";
import QRCode from "qrcode";

type RouteContext = { params: Promise<{ id: string }> };

export async function GET(request: NextRequest, ctx: RouteContext) {
  try {
    const session = await requireApiAuthWithOrg();
    const { id } = await ctx.params;

    const template = await prisma.formTemplate.findUnique({
      where: { id },
      include: {
        organization: { select: { slug: true } },
      },
    });

    if (!template || template.organizationId !== session.user.orgId) {
      return new Response("Not found", { status: 404 });
    }

    const baseUrl = getSiteUrlFromRequest(request);

    const surveyUrl = `${baseUrl}/s/${template.organization.slug}/${template.slug}`;

    const pngBuffer = await QRCode.toBuffer(surveyUrl, {
      type: "png",
      width: 400,
      margin: 2,
    });

    return new Response(new Uint8Array(pngBuffer), {
      headers: {
        "Content-Type": "image/png",
        "Cache-Control": "public, max-age=3600",
      },
    });
  } catch (error) {
    return handleApiError(error);
  }
}
