'use strict';

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

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

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

    if (config.provider !== 'caas' || !config.fqdn) {
        console.log('Not caas (%s) or no fqdn', config.provider, config.fqdn);
        return;
    }

    const result = await db.runSql('SELECT COUNT(*) AS total FROM users');

    if (result[0].total === 0) {
        console.log('This cloudron is not activated. It will automatically get appstore and caas configs from autoprovision logic');
        return;
    }

    console.log('Downloading appstore and caas config');

    const response = await superagent.get(config.apiServerOrigin + `/api/v1/boxes/${config.fqdn}/config`)
        .query({ token: config.token })
        .timeout(30 * 1000);

    console.log('Adding %j config', response.body);

    await db.runSql('INSERT settings (name, value) VALUES(?, ?)', [ 'appstore_config', JSON.stringify(response.body.appstoreConfig) ]);
    await db.runSql('INSERT settings (name, value) VALUES(?, ?)', [ 'caas_config', JSON.stringify(response.body.caasConfig) ]);
};

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