const axios = require("axios")
const fs = require("fs")
var { parse } = require("csv-parse")
var usersArray = []

var api_key = "" // INSERT API KEY

function wait(ms) {
  return new Promise((r) => setTimeout(r, ms))
}

function bulkAddPeople(xApiKey, users, num) {
  let page = num

  axios({
    method: "post",
    url: "https://api.northpass.com/v2/bulk/people",
    data: {
      data: {
        attributes: {
          people: [{ email: users[num].email, groups: users[num].group }],
        },
      },
    },
    headers: {
      accept: "application/json",
      "x-api-key": xApiKey,
      "content-type": "application/json",
    },
  })
    .then((res) => {
      if (page < users.length - 1) {
        console.log(`User ${users[num].email} added to group ${users[num].group} on index ${page}`)
        page++
        wait(200)
        bulkAddPeople(xApiKey, users, page)
      } else {
        console.log("complete")
      }
    })
    .catch((err) => {
      console.log(err)
    })
}

const csvReader = async () => {
  fs.createReadStream("./csv-files/drofus-users.csv") // UPDATE URL OF CSV FILE
    .pipe(parse({ delimiter: "," }))
    .on("data", function (row) {
      const userObj = {
        email: row[3], // UPDATE COLUMN INDEX
        group: row[7]  // UPDATE COLUMN INDEX
      }
      usersArray.push(userObj)
    })
    .on("error", function (error) {
      console.log(error.message)
    })
    .on("end", async function () {
      console.log(`Number of emails in array: ${usersArray.length}`)

      bulkAddPeople(api_key, usersArray, 1) // Start with index 1 if there is a header row, otherwise start with 0
    })
}

csvReader()
