import { NextResponse } from "next/server";
import { createAdminLoginCode, verifyAdminCredentials } from "@/lib/admin-auth";
import { getClientIp } from "@/lib/auth";
import { checkRateLimit } from "@/lib/security";

const GENERIC_MESSAGE = "Wenn E-Mail und Passwort stimmen, wurde ein Einmalcode an die angegebene E-Mail gesendet.";

export async function POST(request: Request) {
  const ip = getClientIp();
  const limited = await checkRateLimit({ key: ip, action: "admin-login", limit: 5, windowSeconds: 60 * 15 });
  if (!limited.ok) {
    return NextResponse.json({ ok: false, error: "Zu viele Admin-Login-Versuche. Bitte später erneut versuchen." }, { status: 429 });
  }

  const body = (await request.json()) as { email?: string; password?: string };
  const email = String(body.email ?? "").trim().toLowerCase();
  const password = String(body.password ?? "");

  if (verifyAdminCredentials(email, password)) {
    await createAdminLoginCode();
  }

  return NextResponse.json({ ok: true, message: GENERIC_MESSAGE });
}
