import { NextRequest, NextResponse } from "next/server";
import { requireAuth, getClientMetadata } from "@/lib/admin/auth";
import { db } from "@/lib/admin/db";
import { verifyTOTP, generateBackupCodes, hashBackupCode } from "@/lib/admin/totp";

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

    if (!secret || !code) {
      return NextResponse.json(
        { error: "Both the secret and the 6-digit verification code are required." },
        { status: 400 }
      );
    }

    const isValid = verifyTOTP(code, secret);
    if (!isValid) {
      return NextResponse.json(
        { error: "Invalid 6-digit authenticator code. Please check your app and try again." },
        { status: 400 }
      );
    }

    // Generate 10 single-use backup recovery codes
    const rawBackupCodes = generateBackupCodes(10);
    const hashedBackupCodes = rawBackupCodes.map(hashBackupCode);

    // Save to user account
    await db.updateUser(auth.user.id, {
      twoFactorEnabled: true,
      twoFactorSecret: secret,
      twoFactorBackupCodes: hashedBackupCodes,
    });

    const { ip } = getClientMetadata(req);
    await db.logSecurityEvent({
      actorId: auth.user.id,
      actorName: auth.user.name,
      actorEmail: auth.user.email,
      actorLevel: auth.user.level,
      targetUserId: auth.user.id,
      targetUserEmail: auth.user.email,
      targetUserName: auth.user.name,
      action: "TWO_FACTOR_ENABLED",
      details: { method: "TOTP_AUTHENTICATOR", backupCodesGenerated: 10 },
      ipAddress: ip,
    });

    return NextResponse.json({
      success: true,
      backupCodes: rawBackupCodes,
    });
  } catch (err: any) {
    console.error("[api/admin/auth/2fa/verify] Error:", err);
    return NextResponse.json(
      { error: err.message || "Failed to verify 2FA code." },
      { status: err.status || 500 }
    );
  }
}
