'use strict';

const fs = require('node:fs'),
    superagent = require('@cloudron/superagent');

exports.up = async function(db) {
    if (!fs.existsSync('/etc/cloudron/cloudron.conf')) {
        console.log('Unable to locate cloudron.conf');
        return;
    }

    const config = JSON.parse(fs.readFileSync('/etc/cloudron/cloudron.conf', 'utf8'));

    const results = await db.all('SELECT * FROM settings WHERE name="appstore_config"');

    if (results.length === 0) {
        console.log('No appstore config, skipping license migration');
        return;
    }

    console.log('Downloading license');

    const appstoreConfig = JSON.parse(results[0].value);

    const response = await superagent.get(`${config.apiServerOrigin}/api/v1/cloudron_license`)
            .query({ accessToken: appstoreConfig.token, cloudronId: appstoreConfig.cloudronId, provider: config.provider })
            .timeout(30 * 1000);

    if (response.status !== 200) throw new Error(`Bad status getting license: ${response.status} ${response.text}`);

    if (!response.body.cloudronId || !response.body.licenseKey || !response.body.cloudronToken) throw new Error(`Bad response getting license:  ${response.text}`);

    console.log('Adding license', response.body);

    await db.runSql('START TRANSACTION;');
    await db.runSql('INSERT settings (name, value) VALUES(?, ?)', [ 'cloudron_id', response.body.cloudronId ]);
    await db.runSql('INSERT settings (name, value) VALUES(?, ?)', [ 'license_key', response.body.licenseKey ]);
    await db.runSql('INSERT settings (name, value) VALUES(?, ?)', [ 'cloudron_token', response.body.cloudronToken ]);
    await db.runSql('DELETE FROM settings WHERE name=?', [ 'appstore_config' ]);
    await db.runSql('COMMIT');
};

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