import { NextRequest, NextResponse } from "next/server";
import { db, featureUpgradeClicks } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";
import { z } from "zod";

const Schema = z.object({
  featureKey: z.string().min(1).max(100),
});

// Fired (best-effort, fire-and-forget from the client) when a user clicks
// "I'm interested" on a locked-feature upgrade dialog — purely a signal for
// Admin -> Insights ("most-requested locked features"), not a purchase or
// a support ticket. Never blocks the redirect to billing on the client.
export async function POST(req: NextRequest) {
  const { session, response } = await requireSession();
  if (response) return response;

  const limited = await applyRateLimit(`rl:upgrade-interest:${session!.user.id}`, 20, 60);
  if (limited) return limited;

  const parsed = Schema.safeParse(await req.json().catch(() => null));
  if (!parsed.success) {
    return NextResponse.json({ error: "Invalid request" }, { status: 400 });
  }

  await db.insert(featureUpgradeClicks).values({
    id: crypto.randomUUID(),
    userId: session!.user.id,
    featureKey: parsed.data.featureKey,
  });

  return NextResponse.json({ ok: true }, { status: 201 });
}
