const customerKey = "51BNlRsLYKQxSu1q1UQq7F63j"

function getCustomerCourses() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Customer Academy");
  sheet.getRange(1,1,500,10).clearContent();
  sheet.getRange(1,1).setValue("Course Name")
  sheet.getRange(1,2).setValue("Course UUID")
  sheet.getRange(1,3).setValue("Enrollments")
  sheet.getRange(1,4).setValue("Created At")
  sheet.getRange(1,5).setValue("Updated At")
  sheet.getRange(1,6).setValue("Status")
  sheet.getRange(1,7).setValue("Unpublished Changes?")
  sheet.getRange(1,8).setValue("Short Description")

  let page = 0
  while (page >= 0) {
    page++
    Logger.log(page)
    var apiURL = 'https://api.northpass.com/v2/courses?limit=100&page='+page;
    const settings = {
    async: true,
    crossDomain: true,
    method: 'GET',
    headers: {
      accept: 'application/json',
      'X-Api-Key': customerKey
    }
  };
    const sendMsg = UrlFetchApp.fetch(apiURL, settings);
    var txtResponse = sendMsg.getContentText();
    var parseProps = JSON.parse(txtResponse);
    
    for (items of parseProps['data']) {
      let courseName = items['attributes']['name']
      let uuid = items['id']
      let createdAt = items['attributes']['created_at']
      let updatedAt = items['attributes']['updated_at']
      let enrollments = items['attributes']['enrollments_count']
      let status = items['attributes']['status']
      let unpublished_changes = items['attributes']['unpublished_changes']
      let short_description = items['attributes']['short_description']
      
      var lastRow = Math.max(sheet.getLastRow(),1);
      sheet.insertRowAfter(lastRow);
      sheet.getRange(lastRow + 1, 1).setValue(courseName);
      sheet.getRange(lastRow + 1, 2).setValue(uuid);
      sheet.getRange(lastRow + 1, 3).setValue(enrollments);
      sheet.getRange(lastRow + 1, 4).setValue(createdAt);
      sheet.getRange(lastRow + 1, 5).setValue(updatedAt);
      sheet.getRange(lastRow + 1, 6).setValue(status);
      sheet.getRange(lastRow + 1, 7).setValue(unpublished_changes);
      sheet.getRange(lastRow + 1, 8).setValue(short_description);
  
    }
    if (parseProps["links"]["next"] == null) {
      break;
    }
  }
}
