import { NextRequest, NextResponse } from "next/server";
import { getClientMetadata } from "@/lib/admin/auth";
import { db, hashPassword } from "@/lib/admin/db";

export const dynamic = "force-dynamic";

/**
 * POST /api/admin/auth/reset-password
 * Consumes a single-use token to establish a new password for the administrator account.
 */
export async function POST(req: NextRequest) {
  try {
    const body = await req.json().catch(() => ({}));
    const token = typeof body.token === "string" ? body.token.trim() : "";
    const newPassword = typeof body.newPassword === "string" ? body.newPassword : "";
    const confirmPassword = typeof body.confirmPassword === "string" ? body.confirmPassword : "";

    if (!token) {
      return NextResponse.json(
        { error: "Password reset token is missing or invalid." },
        { status: 400 }
      );
    }

    if (!newPassword || newPassword.length < 8) {
      return NextResponse.json(
        { error: "Password must be at least 8 characters long." },
        { status: 400 }
      );
    }

    if (newPassword !== confirmPassword) {
      return NextResponse.json(
        { error: "New password and confirmation password do not match." },
        { status: 400 }
      );
    }

    // Verify token validity
    const tokenRecord = await db.verifyPasswordResetToken(token);
    if (!tokenRecord) {
      return NextResponse.json(
        { error: "Password reset link is invalid, expired, or has already been used." },
        { status: 400 }
      );
    }

    const user = await db.getUserById(tokenRecord.userId);
    if (!user || user.status !== "ACTIVE") {
      return NextResponse.json(
        { error: "User account associated with this token is invalid or disabled." },
        { status: 403 }
      );
    }

    // Hash new password
    const { hash, salt } = hashPassword(newPassword);

    await db.updateUser(user.id, {
      passwordHash: hash,
      passwordSalt: salt,
      passwordChangeRequired: false,
    });

    // Mark token as consumed
    await db.consumePasswordResetToken(token);

    // Invalidate all active sessions for security
    const activeSessions = await db.getActiveSessionsForUser(user.id);
    for (const sess of activeSessions) {
      await db.revokeSession(sess.tokenHash, "PASSWORD_RESET", user.id);
    }

    const { ip } = getClientMetadata(req);
    await db.logSecurityEvent({
      actorId: user.id,
      actorName: user.name,
      actorEmail: user.email,
      actorLevel: user.level,
      targetUserId: user.id,
      targetUserEmail: user.email,
      targetUserName: user.name,
      action: "PASSWORD_RESET_COMPLETED",
      details: {
        note: "Password successfully updated via single-use reset token.",
      },
      ipAddress: ip,
    });

    return NextResponse.json({
      ok: true,
      message: "Password reset successful. Please sign in with your new credentials.",
    });
  } catch (err: any) {
    console.error("[POST /api/admin/auth/reset-password] Error:", err);
    return NextResponse.json(
      { error: err.message || "Failed to reset password." },
      { status: 500 }
    );
  }
}
