// JavaScript Document
// throwing 500 error
exports.onesignal_create_segment = async function (options) {
    const { v4: uuidv4 } = require("uuid");

    const uuid = uuidv4();
    //console.log(`UUID: ${uuid}`);
    // get appid
    const appid = this.parseOptional(options.appid, '*', process.env.ONESIGNAL_APP_ID);
    console.log(options.appid + " => " + appid);

    const segname = this.parseRequired(options.segname, '*', 'No segment name specified');
    console.log(options.segname + " => " + segname);

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

    const seguuid = this.parseOptional(options.seguuid, '*', uuid);
    console.log("seguuid: " + options.seguuid + " => " + seguuid);

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

    const url = `https://api.onesignal.com/apps/${appid}/segments`;
    const os_options = {
        method: 'POST',
        headers: {
            accept: 'application/json',
            Authorization: `Basic ${process.env.ONESIGNAL_REST_API_KEY}`,
            'Content-Type': 'application/json; charset=utf-8'
        },
        body: JSON.stringify({ name: segname, 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));

}




