import { redirect, notFound } from "next/navigation";
import { NextRequest } from "next/server";
import { resolveAndTrackRedirect } from "../../lib/payload";

// A static short link (e.g. printed on a QR code) that always resolves to
// whatever `targetPath` is currently set on the matching Redirects document
// in Payload — the QR code itself never needs reprinting when the target
// changes. `redirect()` (not permanentRedirect()) issues a 307, deliberately
// non-cacheable client-side since the target can change at any time.
export async function GET(_request: NextRequest, { params }: { params: Promise<{ code: string }> }) {
  const { code } = await params;
  const targetPath = await resolveAndTrackRedirect(code, "/r");

  // Defense in depth — Redirects.targetPath is already validated in Payload
  // to start with "/", same open-redirect guard as api/preview/route.ts.
  if (!targetPath || !targetPath.startsWith("/") || targetPath.startsWith("//")) {
    notFound();
  }

  redirect(targetPath);
}
