/**
* @api {post} /api/users Create New User
* @apiName CreateUser
* @apiGroup Users
* @apiPermission authenticated
*
* @apiDescription Creates a new user account in the system. Requires valid authentication token.
*
* @apiHeader {String} Authorization Bearer <token>
*
* @apiBody {String} username Unique username for the new user (required)
* @apiBody {String} email Valid email address (required)
* @apiBody {String} password Password string (minimum 8 characters recommended)
*
* @apiSuccess (201) {String} message Confirmation message
* @apiSuccess (201) {String} userId ID of the newly created user
*
* @apiError (400) BadRequest Missing required fields (username, email, or password)
* @apiError (401) Unauthorized Missing or invalid authentication token
* @apiError (409) Conflict User with this email already exists
* @apiError (500) InternalServerError Database or server error
*
* @apiExample {curl} Example usage:
* curl -X POST https://api.example.com/api/users \
* -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..." \
* -H "Content-Type: application/json" \
* -d '{"username":"john_doe","email":"john@example.com","password":"securePassword123"}'
*
* @apiSuccessExample {json} Success Response:
* HTTP/1.1 201 Created
* {
* "message": "User created successfully",
* "userId": "5f9d3b1c4a8e5c2d1a2b3c4d5e6f"
* }
*
* @apiErrorExample {json} Error Response:
* HTTP/1.1 400 Bad Request
* {
* "error": "Username, email, and password are required"
* }
*/
router.post('/api/users', authenticateToken, async (req, res) => {
try {
const { username, email, password } = req.body;
// Validate required fields
if (!username || !email || !password) {
return res.status(400).json({ error: 'Username, email, and password are required' });
}
// Check if user already exists
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(409).json({ error: 'User with this email already exists' });
}
// Hash password and create user
const hashedPassword = await bcrypt.hash(password, 10);
const user = new User({ username, email, password: hashedPassword });
await user.save();
res.status(201).json({ message: 'User created successfully', userId: user._id });
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});