import { NextResponse } from "next/server";
import { listGames } from "@/lib/games";

/**
 * Live search suggestions: up to 6 published games matching q.
 * Minimal payload (slug/title/category) for a fast autocomplete dropdown.
 */

// In-memory per-IP rate limit (60/min). Same single-instance caveat as the
// login limiter; a shared store belongs to a later scaling step.
const SUGGEST_WINDOW_MS = 60 * 1000;
const SUGGEST_MAX = 60;
const hits = new Map<string, { count: number; resetAt: number }>();

function limited(ip: string): boolean {
  const now = Date.now();
  const entry = hits.get(ip);
  if (!entry || now >= entry.resetAt) {
    hits.set(ip, { count: 1, resetAt: now + SUGGEST_WINDOW_MS });
    return false;
  }
  entry.count += 1;
  return entry.count > SUGGEST_MAX;
}

export async function GET(request: Request) {
  const forwarded = request.headers.get("x-forwarded-for");
  const ip = forwarded?.split(",")[0]?.trim() || "unknown";
  if (limited(ip)) {
    return NextResponse.json(
      { suggestions: [], error: "Too many requests." },
      { status: 429, headers: { "Cache-Control": "no-store" } },
    );
  }
  const q = new URL(request.url).searchParams.get("q")?.trim().slice(0, 50) ?? "";
  if (!q) {
    return NextResponse.json({ suggestions: [] });
  }
  const { games } = await listGames({ q, pageSize: 6 });
  return NextResponse.json(
    {
      suggestions: games.map((g) => ({
        slug: g.slug,
        title: g.title,
        categoryName: g.categoryName,
      })),
    },
    { headers: { "Cache-Control": "no-store" } },
  );
}
