import { NextRequest, NextResponse } from "next/server";
import { createAdminClient } from "@/lib/supabase/admin";
import { clientIp, isBot, recordClick, sessionIdFromCookies } from "@/lib/ad-tracking";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

export async function GET(req: NextRequest, { params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const admin = createAdminClient();
  const nowIso = new Date().toISOString();

  const { data, error } = await admin
    .from("banner_creatives")
    .select("id, click_url, status, start_date, end_date")
    .eq("slug", slug)
    .maybeSingle();

  if (error || !data) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const row = data as any;
  const active =
    row.status === "active" &&
    (!row.start_date || row.start_date <= nowIso) &&
    (!row.end_date || row.end_date >= nowIso) &&
    !!row.click_url;
  if (!active) return NextResponse.json({ error: "Not active" }, { status: 410 });

  const ua = req.headers.get("user-agent");
  const referrer = req.headers.get("referer");
  const ip = clientIp(req.headers);
  const sid = sessionIdFromCookies(req.headers.get("cookie"));

  // Fire-and-forget the INSERT — the click target is the most important
  // thing on the response path. If the log write throws, swallow it.
  recordClick({
    campaignId: row.id,
    pageUrl: referrer,
    referrer,
    userAgent: ua,
    ipAddress: ip,
    isBot: isBot(ua),
    sessionId: sid,
  }).catch((err) => console.error("[click] insert failed:", err?.message));

  return NextResponse.redirect(row.click_url, 302);
}
