import { NextResponse } from "next/server";
import { createAdminSession, getAdminEmail } from "@/lib/admin-auth";
import { getClientIp } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { checkRateLimit, sha256 } from "@/lib/security";

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

  const body = (await request.json()) as { email?: string; code?: string };
  const email = String(body.email ?? "").trim().toLowerCase();
  const code = String(body.code ?? "").trim();
  const record = await prisma.adminLoginToken.findUnique({ where: { tokenHash: sha256(code) } });

  if (!record || record.email !== email || record.email !== getAdminEmail() || record.usedAt || record.expiresAt <= new Date()) {
    return NextResponse.json({ ok: false, error: "Code ungültig oder abgelaufen." }, { status: 401 });
  }

  await prisma.adminLoginToken.update({ where: { id: record.id }, data: { usedAt: new Date() } });
  await createAdminSession(record.email);
  return NextResponse.json({ ok: true });
}
