import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { passwordMatches, signSession } from "@/lib/auth/session";
import { buildSessionCookie } from "@/lib/auth/cookie";

// In-Memory Rate-Limit. Genügt für ein Single-User-Backend; nicht für
// öffentliche Auth. Bei Bedarf später durch Redis/SQLite-basiertes Limit ersetzen.
const WINDOW_MS = 15 * 60 * 1000;
const MAX_TRIES = 20;
const tries = new Map<string, { count: number; resetAt: number }>();

function getClientKey(req: NextRequest): string {
  const xff = req.headers.get("x-forwarded-for");
  if (xff) return xff.split(",")[0]?.trim() ?? "unknown";
  return req.headers.get("x-real-ip") ?? "unknown";
}

function checkRate(key: string): { allowed: boolean; retryAfter?: number } {
  const now = Date.now();
  const cur = tries.get(key);
  if (!cur || cur.resetAt < now) {
    tries.set(key, { count: 1, resetAt: now + WINDOW_MS });
    return { allowed: true };
  }
  if (cur.count >= MAX_TRIES) {
    return { allowed: false, retryAfter: Math.ceil((cur.resetAt - now) / 1000) };
  }
  cur.count += 1;
  return { allowed: true };
}

export async function POST(req: NextRequest) {
  const key = getClientKey(req);
  const limit = checkRate(key);
  if (!limit.allowed) {
    return NextResponse.json(
      { error: "rate_limited" },
      { status: 429, headers: { "Retry-After": String(limit.retryAfter ?? 60) } }
    );
  }

  let body: { password?: unknown };
  try {
    body = (await req.json()) as { password?: unknown };
  } catch {
    return NextResponse.json({ error: "bad_request" }, { status: 400 });
  }
  const password = typeof body.password === "string" ? body.password : "";
  if (!password) {
    return NextResponse.json({ error: "bad_request" }, { status: 400 });
  }
  if (!passwordMatches(password)) {
    // Verzögerung gegen Brute-Force (konstant, daher kein Timing-Leak).
    await new Promise((r) => setTimeout(r, 250));
    return NextResponse.json({ error: "invalid" }, { status: 401 });
  }
  const token = signSession();
  const secure = (req.nextUrl.protocol === "https:") || (req.headers.get("x-forwarded-proto") === "https");
  const cookie = buildSessionCookie(token, { secure });
  const res = NextResponse.json({ ok: true });
  res.headers.append("Set-Cookie", cookie);
  return res;
}
