const axios = require("axios")
const fs = require("fs");
const { parse } = require("csv-parse");
//let xApiKey = "XxDBlgH3CNSiD6yDgqZgpjjxB"   // <<< This is for Ausitn's School
let xApiKey = 'HdZFoXGCFpt8NnTOzIQY0kVDj' // <<< This is for sandata's school

let allUsers = [];

fs.createReadStream("./sandataNevadaUsers.csv")
.pipe(parse({ delimiter: ','}))
.on("data", function (row) {

    if(row[0] !== 'Email'){
      allUsers.push({
        email: row[0],
        group: 'ST - Nevada (DHCFP)'
      });
    }
})
.on("error", function (error) {
    console.log(error.message);
})
.on("end", async function () {
    console.log("FINISHED COLLECTING ALL NEW USERS");
    // console.log(allUsers[0]);
    console.log(allUsers.length);

    await executeFunctionChain();
})


let executeFunctionChain = async () => {
  for(let i = 0; i < allUsers.length; i++){
    await axios({
      method: 'post',
      url: 'https://api.northpass.com/v2/bulk/people',
      data: {
        "data": {
          "attributes": {
            "people": [{
              "email": allUsers[i].email,
              // "email": "joojinhyung@gmail.com",
              "groups": allUsers[i].group
              //"groups": [10593ca2-daa7-41fb-ad12-1de77d51fe81] >> wrong, uses name not id
            }]
          }
        }
      },
      headers: {
        'accept': 'application/json',
        'x-api-key': xApiKey,
        'content-type': 'application/json'
      }
    })
    .then((res) => {
      console.log(`SUCCESSFULLY ADDED USER ${allUsers[i].email} TO GROUP ${allUsers[i].group}`)
      console.log(`COMPLETED USER ${i + 1}`)
      // console.log(res.data);
      return;
    })
    .catch((err) => {
      console.log(err.data);
    })
  }
}

