import { NextRequest, NextResponse } from "next/server";
import QRCode from "qrcode";

function isAllowedQrUrl(raw: string): boolean {
  try {
    const parsed = new URL(raw);
    const base =
      process.env.NEXT_PUBLIC_APP_URL ??
      process.env.NEXTAUTH_URL ??
      "http://localhost:3000";
    const allowed = new URL(base);
    return parsed.origin === allowed.origin;
  } catch {
    return false;
  }
}

export async function GET(request: NextRequest) {
  const url = request.nextUrl.searchParams.get("url");
  if (!url) {
    return NextResponse.json({ error: "url required" }, { status: 400 });
  }

  if (!isAllowedQrUrl(url)) {
    return NextResponse.json({ error: "URL not allowed" }, { status: 400 });
  }

  try {
    const png = await QRCode.toBuffer(url, {
      width: 280,
      margin: 2,
      color: { dark: "#0B2545", light: "#FFFFFF" },
    });

    return new NextResponse(new Uint8Array(png), {
      headers: {
        "Content-Type": "image/png",
        "Cache-Control": "public, max-age=86400",
      },
    });
  } catch {
    return NextResponse.json({ error: "QR generation failed" }, { status: 500 });
  }
}
