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

// Branded short link: /s/<code> -> resolve the target via the API, then 302.
export async function GET(req: NextRequest, ctx: { params: Promise<{ code: string }> }) {
  const { code } = await ctx.params;
  const api = process.env.NEXT_PUBLIC_API_URL || "http://localhost:4100/api";
  try {
    const r = await fetch(`${api}/shortlink/${encodeURIComponent(code)}`, { cache: "no-store" });
    const d = (await r.json()) as { url?: string | null };
    if (d?.url) return NextResponse.redirect(d.url, 302);
  } catch {
    /* fall through */
  }
  return NextResponse.redirect(new URL("/", req.url), 302);
}
