// JavaScript Document
//V1.0.0
exports.onesignal_create_sms_notification = async function (options) {
   // get appid
   const appid = this.parseOptional(options.appid, '*', process.env.ONESIGNAL_APP_ID)
   console.log(options.appid + " => " + appid)

   const contents = this.parseRequired(options.contents, '*', 'Bindings Required')
   console.log(options.contents + " => " + contents)

   const sms_from = this.parseOptional(options.sms_from, '*', process.env.ONESIGNAL_SMS_DEFAULT)
   console.log(options.sms_from + " => " + sms_from)

   // get message internal name
   const osname = this.parseOptional(options.osname, '*', 'osname')
   console.log('Name: ' + options.osname + " => " + osname)

   const segment = this.parseOptional(options.segment, '*', 'All')
   console.log("Segment: " + options.segment + " => " + segment)

   const filter = this.parseOptional(options.filter, '*', null)
   console.log("Filter: " + options.filter + " => " + filter)

   const include_phone_numbers = this.parseOptional(options.include_phone_numbers, '*', null)
   console.log("include_phone_numbers: " + options.include_phone_numbers + " => " + include_phone_numbers)

   const fetch = require('node-fetch');

   const url = 'https://api.onesignal.com/notifications?c=sms';
   const os_options = {
      method: 'POST',
      headers: { accept: 'application/json', 'content-type': 'application/json', Authorization: `Basic ${process.env.ONESIGNAL_REST_API_KEY}` },
      body: JSON.stringify({
         contents: contents,
         app_id: appid,
         included_segments: [segment],
         target_channel: 'sms',
         sms_from: sms_from,
         name: osname,
         include_phone_numbers: [include_phone_numbers],
         filters: filter
      }
      )
   };

   return fetch(url, os_options)
      .then(res => {

         return res.json().then(json => {
            json.status = res.status; // Add status to json response
            return json;
         });
      })
      .catch(err => console.error('Error:', err));

}
