import { NextResponse } from "next/server";
import { createHash } from "crypto";
import { sql } from "@/db";

export async function POST(request: Request, { params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const { productId } = await request.json();
  if (!productId) return NextResponse.json({ error: "productId required" }, { status: 400 });

  // verify product belongs to this slug's profile
  const check = await sql`
    SELECT rp.url FROM recommended_products rp
    JOIN member_profiles mp ON mp.id = rp.profile_id
    WHERE rp.id = ${productId} AND mp.slug = ${slug} AND rp.is_active = true
    LIMIT 1
  `;
  if (!check[0]) return NextResponse.json({ error: "Product not found" }, { status: 404 });

  const forwarded = request.headers.get("x-forwarded-for") ?? "unknown";
  const ip = forwarded.split(",")[0].trim();
  const ipHash = createHash("sha256").update(ip).digest("hex");
  const referrer = request.headers.get("referer") ?? null;

  await sql`
    INSERT INTO product_clicks (product_id, referrer, ip_hash)
    VALUES (${productId}, ${referrer}, ${ipHash})
  `;

  return NextResponse.json({ url: check[0].url });
}
