import { NextResponse, type NextRequest } from "next/server";
import { answerQuestion, type ChatTurn } from "@/lib/ai/chat";

/**
 * Public assistant endpoint for the landing page.
 *
 * Open to anonymous visitors by design — it answers only from published TECH-C
 * material, never from database records. A per-IP sliding window keeps the
 * endpoint from being used as a free model proxy.
 */

const WINDOW_MS = 60_000;
const MAX_REQUESTS_PER_WINDOW = 12;
const MAX_BODY_BYTES = 8_000;

// Process-local counters: adequate for a single instance, and it fails open
// rather than blocking real visitors if the map is cold.
const hits = new Map<string, number[]>();

function rateLimited(ip: string): boolean {
  const now = Date.now();
  const recent = (hits.get(ip) ?? []).filter((t) => now - t < WINDOW_MS);
  recent.push(now);
  hits.set(ip, recent);

  // Opportunistic sweep so the map cannot grow without bound.
  if (hits.size > 500) {
    for (const [key, times] of hits) {
      if (times.every((t) => now - t >= WINDOW_MS)) hits.delete(key);
    }
  }

  return recent.length > MAX_REQUESTS_PER_WINDOW;
}

function parseTurns(raw: unknown): ChatTurn[] {
  if (!Array.isArray(raw)) return [];
  return raw
    .filter(
      (t): t is ChatTurn =>
        Boolean(t) &&
        typeof t === "object" &&
        "role" in t &&
        "content" in t &&
        (t.role === "user" || t.role === "assistant") &&
        typeof t.content === "string"
    )
    .slice(-8)
    .map((t) => ({ role: t.role, content: t.content.slice(0, 600) }));
}

export async function POST(request: NextRequest) {
  // Prefer the right-most hop a trusted proxy appended: the left-most value in
  // `x-forwarded-for` is whatever the client sent and is trivially spoofed,
  // which would let one caller mint a new identity per request and use this
  // endpoint as a free model proxy. `x-real-ip` is set by nginx and is not
  // client-controllable in the deployment; it is the better single source.
  const ip =
    request.headers.get("x-real-ip")?.trim() ||
    request.headers.get("x-forwarded-for")?.split(",").pop()?.trim() ||
    "unknown";

  if (rateLimited(ip)) {
    return NextResponse.json(
      { error: "Terlalu banyak pertanyaan. Tunggu sebentar, lalu coba lagi." },
      { status: 429, headers: { "Retry-After": "60" } }
    );
  }

  const raw = await request.text();
  if (raw.length > MAX_BODY_BYTES) {
    return NextResponse.json({ error: "Pertanyaan terlalu panjang." }, { status: 413 });
  }

  let body: unknown;
  try {
    body = JSON.parse(raw);
  } catch {
    return NextResponse.json({ error: "Format permintaan tidak valid." }, { status: 400 });
  }

  if (!body || typeof body !== "object" || !("question" in body)) {
    return NextResponse.json({ error: "Pertanyaan tidak boleh kosong." }, { status: 400 });
  }

  const question = body.question;
  if (typeof question !== "string" || question.trim().length === 0) {
    return NextResponse.json({ error: "Pertanyaan tidak boleh kosong." }, { status: 400 });
  }

  const history = "history" in body ? parseTurns(body.history) : [];
  const reply = await answerQuestion(question, history);

  return NextResponse.json(reply, {
    headers: { "Cache-Control": "no-store" },
  });
}
