import { NextRequest, NextResponse } from "next/server";
import { requireAuth, getClientMetadata } from "@/lib/admin/auth";
import { db, verifyPassword } from "@/lib/admin/db";
import { verifyTOTP, verifyAndConsumeBackupCode } 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 : "";
    const code = typeof body.code === "string" ? body.code.trim() : "";

    if (!password || !code) {
      return NextResponse.json(
        { error: "Both your password and a 2FA code (or backup code) are required to disable 2FA." },
        { status: 400 }
      );
    }

    // 1. Re-authenticate password
    const isPasswordValid = verifyPassword(password, auth.user.passwordHash, auth.user.passwordSalt);
    if (!isPasswordValid) {
      return NextResponse.json(
        { error: "Incorrect password." },
        { status: 401 }
      );
    }

    // 2. Verify either TOTP code or backup code
    let is2FAValid = false;
    if (auth.user.twoFactorSecret && /^\d{6}$/.test(code)) {
      is2FAValid = verifyTOTP(code, auth.user.twoFactorSecret);
    }

    if (!is2FAValid) {
      // Try backup code
      is2FAValid = await verifyAndConsumeBackupCode(auth.user, code);
    }

    if (!is2FAValid) {
      return NextResponse.json(
        { error: "Invalid 2FA verification code or backup code." },
        { status: 400 }
      );
    }

    // Disable 2FA
    await db.updateUser(auth.user.id, {
      twoFactorEnabled: false,
      twoFactorSecret: null,
      twoFactorBackupCodes: [],
    });

    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_DISABLED",
      details: { disabledBy: auth.user.email },
      ipAddress: ip,
    });

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