Source: user-helpers-comments.js

const fs = require("fs");

const path = __dirname + "/../users.json";
console.log("User data will be stored in this file: ", path);

/**
 * Saves an array of user objects to the JSON file.
 * 
 * @param {Array<Object>} users - The array of user objects to save.
 */
function saveUsers(users){
    const json = JSON.stringify(users, null, 2);
    fs.writeFileSync(path, json);
}

/**
 * Retrieves all users from the JSON file.
 * 
 * @returns {Array<Object>} - An array of all users.
 */
function getAllUsers(){
    const usersJSON = fs.readFileSync(path, "utf-8");
    return JSON.parse(usersJSON);
}

/**
 * Adds a new user to the list of users stored in the JSON file.
 * 
 * @param {Object} user - The user object to add.
 * @param {string} user.email - The email of the user.
 * @param {string} user.password - The password of the user.
 * @param {string} [user.name] - The optional name of the user.
 */
function addUser(user){
    const users = getAllUsers();
    users.push(user);
    saveUsers(users);
}

/**
 * Retrieves a user by their email address.
 * 
 * @param {string} email - The email of the user to retrieve.
 * @returns {Object|null} - The user object if found, otherwise null.
 */
function getUserByEmail(email){
    const users = getAllUsers();
    return users.find(u => u.email === email) || null;
}

/**
 * Attempts to log in a user by matching the email and password.
 * 
 * @param {string} email - The email of the user trying to log in.
 * @param {string} password - The password of the user trying to log in.
 * @returns {Object|boolean} - The user object if login is successful, otherwise false.
 */
function login(email, password){
    const user = getUserByEmail(email);
    if(user && user.password === password){
        return user;
    }
    return false;
}