// JavaScript Document
exports.onesignal_unsubscribe_email = 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 notification_id = this.parseRequired(options.notification_id, '*', 'Notification ID not specified')
    console.log('notification_id: ' + options.notification_id + " => " + notification_id)

    var token = this.parseRequired(options.token, '*', 'Token not specified')
    console.log('Token: ' + options.token + " => " + token)
    const fetch = require('node-fetch');

    const url = `https://api.onesignal.com/apps/${appid}/notifications/${notification_id}/unsubscribe?token=${token}`;
    const os_options = { method: 'POST', headers: { accept: 'application/json', Authorization: `Basic ${process.env.ONESIGNAL_REST_API_KEY}`, } };

    return fetch(url, os_options)
        .then(res => {
            if (!res.ok) {
                throw new Error(`HTTP error! status: ${res.status}`);
            }
            return res.json().then(json => {
                json.status = res.status; // Add status to json response
                return json;
            });
        })
        .catch(err => console.error('Error:', err));
}

