// JavaScript Document
//v1.0.0
// schema missing in response?
exports.onesignal_create_subscription = async function (options) {
    // get appid parsed as options.appid, throw error is missing
    const appid = this.parseRequired(options.appid, '*', 'No app ID entered')
    // log before and after vlaues
    console.log('App id: ' + options.appid + " => " + appid)

    //var subscription_id = this.parseRequired(options.subscription_id, '*', 'Subscription ID not specified')
    // console.log('Subscription_id: ' + options.subscription_id + " => " + subscription_id)

    var token = this.parseRequired(options.token, '*', 'Token not specified')
    console.log('Token: ' + options.token + " => " + token)

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

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

    const pushtype = this.parseRequired(options.pushtype, '*', 'No push type specified')
    console.log('Type: ' + options.pushtype)

    const enabled = this.parseOptional(options.enabled, '*', false)
    console.log('Enabled: ' + options.enabled + " => " + enabled)

    const notification_types = enabled ? 1 : -99

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

    const url = `https://api.onesignal.com/apps/${appid}/users/by/${alias_label}/${alias_id}/subscriptions`;
    const os_options = {
        method: 'POST',
        headers: { accept: 'application/json', 'content-type': 'application/json', Authorization: `Basic ${process.env.ONESIGNAL_REST_API_KEY}` },
        body: JSON.stringify(
            Object.fromEntries(
                Object.entries({
                    subscription: {
                        type: pushtype,
                        token: token,
                        alias_label: alias_label,
                        alias_id: alias_id,
                        enabled: enabled,
                        notification_types: notification_types
                    }
                }).filter(([_, v]) => v != null)
            ))
    };
    console.log(os_options)

    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));
}
