let STORE = {
   posts: [],
   users: [],
   nextFreeUserId: 0,
   nextFreePostId: 0
}

function resetStore() {
   STORE = {
      posts: [],
      users: [],
      nextFreeUserId: 1,
      nextFreePostId: 1
   };

   addPost("IGCTF{BigTechWillnOtSiLenceUs}", 1);
   addUser("moderator", "916027bd3a6e3d7131f98d9997db1931a146c2b97f2eb7de75b9bbfb9ed91fb432742e7aea628eafb5ad56027132f7b71fa0");
}

function createPost(body, by, id) {
   return {
      id,
      by,
      body
   }
}

function createUser(username, password, id) {
   return {
      username, 
      password,
      id
   }
}

function addPost(body, by) {
   STORE.posts.push(createPost(body, by, STORE.nextFreePostId))
   STORE.nextFreePostId += 1
}

function addUser(username, password) {
   STORE.users.push(createUser(username, password, STORE.nextFreeUserId))
   STORE.nextFreeUserId += 1
}

function checkLogin(username, password) {
   let found = false;
   STORE.users.forEach((user) => {
      if (user.username === username && user.password === password) {
         found = user.id;
      }
   });

   return found;
}

function registerUser(username, password) {
   let found = false;
   STORE.users.forEach((user) => {
      if (user.username == username) {
         found = true;
      }
   });

   if (found) {
      return "user already exists";
   } else {
      addUser(username, password);
      return null;
   }
}

function getPostsBy(userId) {
   return STORE.posts.filter((post) => post.by === userId);
}  

function getPostById(id) {
   return STORE.posts.filter((post) => post.id == id)[0]
}

function isModerator(id) {
   return id === 1;
}

function getAllPosts() {
   return STORE.posts;
}

module.exports = {
   resetStore,
   addPost,
   addUser,
   checkLogin,
   registerUser,
   getPostsBy,
   getPostById,
   isModerator,
   getAllPosts,
}
