'use strict';

const superagent = require('@cloudron/superagent');

exports.up = async function(db) {
    const results1 = await db.runSql('SELECT value FROM settings WHERE name="api_server_origin"');
    if (results1.length === 0) return;
    const apiServerOrigin = results1[0].value;

    const results2 = await db.runSql('SELECT value FROM settings WHERE name="appstore_api_token"');
    if (results2.length === 0) return;
    const apiToken = results2[0].value;

    console.log(`Getting appstore web token from ${apiServerOrigin}`);

    const response = await superagent.post(`${apiServerOrigin}/api/v1/user_token`)
        .send({})
        .query({ accessToken: apiToken })
        .timeout(30 * 1000)
        .ok(() => true);

    if (response.status !== 201 || !response.body.accessToken) {
        console.log(`Bad status getting web token: ${response.status} ${response.text}`);
        return;
    }

    await db.runSql('INSERT settings (name, value) VALUES(?, ?)', [ 'appstore_web_token', response.body.accessToken ]);
};

exports.down = function(db, callback) {
    callback();
};
