export async function registerRoutes(app: Express): Promise<Server> {
  console.log("Starting routes registration...");


  // Increase bodyParser limits
  app.use(express.json({ limit: '50mb' }));
  app.use(express.urlencoded({ limit: '50mb', extended: true }));

  try {
    setupAuth(app);
    console.log("✅ Auth setup completed");

    // Register new user
    app.post("/api/register", async (req, res, next) => {
      try {
        console.log("Received registration request with body:", req.body);

        const existingUser = await storage.getUserByUsername(req.body.username);
        console.log("Existing user check result:", !!existingUser);

        if (existingUser) {
          console.log("Registration failed: Username already exists");
          return res.status(400).json({ message: "Username already exists" });
        }

        console.log("Validating user data...");
        const validated = req.body;
        console.log("Data validation successful");

        console.log("Creating new user in database...");
        const user = await storage.createUser({
          ...validated,
          password: await hashPassword(validated.password),
        });
        console.log("User created successfully:", { id: user.id, username: user.username });

        req.login(user, (err) => {
          if (err) {
            console.error("Login after registration failed:", err);
            return next(err);
          }
          console.log("User logged in successfully after registration");
          res.status(201).json(user);
        });
      } catch (error) {
        console.error("Registration error:", error);
        const message = error instanceof Error ? error.message : "Registration failed";
        res.status(400).json({ message });
      }
    });

    console.log("✅ Routes registered successfully");
    const httpServer = createServer(app);
    return httpServer;
  } catch (error) {
    console.error("❌ Error in routes registration:", error);
    throw error;
  }
}