import { NextRequest, NextResponse } from "next/server";
import { getSession, setUserPassword } from "@/lib/auth";

interface ChangePasswordBody {
  password: string;
  userId?: string;
}

export async function POST(req: NextRequest) {
  let body: ChangePasswordBody;

  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ error: "Invalid request body." }, { status: 400 });
  }

  const { password, userId } = body;

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

  // Get the current session
  const { data: session } = await getSession();
  const sessionUserId = session?.user?.id;

  if (!sessionUserId) {
    return NextResponse.json(
      { error: "Not authenticated." },
      { status: 401 }
    );
  }

  // If userId is provided, require admin privileges (handled by updatePasswordAction)
  // If no userId, the user is changing their own password
  const targetUserId = userId ?? sessionUserId;

  // Non-admin users can only change their own password
  if (userId && userId !== sessionUserId) {
    // For now, only admins can change other users' passwords
    // This is handled by the updatePasswordAction in admin/password.ts
    return NextResponse.json(
      { error: "Use the admin panel to change other users' passwords." },
      { status: 403 }
    );
  }

  try {
    const result = await setUserPassword({
      userId: targetUserId,
      newPassword: password,
    });

    if (result.error) {
      console.error("[auth/change-password] Failed:", result.error);
      return NextResponse.json(
        {
          error: result.error.code ?? "ChangeFailed",
          message: result.error.message ?? "Failed to change password.",
        },
        { status: 400 }
      );
    }

    console.log("[auth/change-password] Password changed for user:", targetUserId);
    return NextResponse.json({ success: true });
  } catch (err) {
    console.error("[auth/change-password] Unexpected error:", err);
    return NextResponse.json(
      { error: "InternalError", message: "An unexpected error occurred." },
      { status: 500 }
    );
  }
}
