import { NextRequest, NextResponse } from "next/server";
import { requireAuth } from "@/lib/admin/auth";
import { verifyPassword } from "@/lib/admin/db";
import { generateTOTPEnrollment } from "@/lib/admin/totp";

export async function POST(req: NextRequest) {
  try {
    const auth = await requireAuth(req);
    const body = await req.json().catch(() => ({}));
    const password = typeof body.password === "string" ? body.password : "";

    if (!password) {
      return NextResponse.json(
        { error: "Current password is required to enroll in 2FA." },
        { status: 400 }
      );
    }

    // Verify current password for re-authentication
    const isValid = verifyPassword(password, auth.user.passwordHash, auth.user.passwordSalt);
    if (!isValid) {
      return NextResponse.json(
        { error: "Incorrect password. Authentication failed." },
        { status: 401 }
      );
    }

    // Generate real TOTP secret, uri, and scannable QR code
    const enrollment = await generateTOTPEnrollment(auth.user.email);

    return NextResponse.json({
      secret: enrollment.secret,
      otpauthUri: enrollment.otpauthUri,
      qrCodeDataUrl: enrollment.qrCodeDataUrl,
    });
  } catch (err: any) {
    console.error("[api/admin/auth/2fa/enroll] Error:", err);
    return NextResponse.json(
      { error: err.message || "Failed to initiate 2FA enrollment." },
      { status: err.status || 500 }
    );
  }
}
