import assert from 'node:assert';
import database from './database.js';


async function unset(appId, addonId) {
    assert.strictEqual(typeof appId, 'string');
    assert.strictEqual(typeof addonId, 'string');

    await database.query('DELETE FROM appAddonConfigs WHERE appId = ? AND addonId = ?', [ appId, addonId ]);
}

async function set(appId, addonId, env) {
    assert.strictEqual(typeof appId, 'string');
    assert.strictEqual(typeof addonId, 'string');
    assert(Array.isArray(env));

    await unset(appId, addonId);
    if (env.length === 0) return;

    const query = 'INSERT INTO appAddonConfigs(appId, addonId, name, value) VALUES ';
    const args = [ ], queryArgs = [ ];
    for (let i = 0; i < env.length; i++) {
        args.push(appId, addonId, env[i].name, env[i].value);
        queryArgs.push('(?, ?, ?, ?)');
    }

    await database.query(query + queryArgs.join(','), args);
}

async function unsetByAppId(appId) {
    assert.strictEqual(typeof appId, 'string');

    await database.query('DELETE FROM appAddonConfigs WHERE appId = ?', [ appId ]);
}

async function get(appId, addonId) {
    assert.strictEqual(typeof appId, 'string');
    assert.strictEqual(typeof addonId, 'string');

    const results = await database.query('SELECT name, value FROM appAddonConfigs WHERE appId = ? AND addonId = ?', [ appId, addonId ]);
    return results;
}

async function getByAppId(appId) {
    assert.strictEqual(typeof appId, 'string');

    const results = await database.query('SELECT name, value FROM appAddonConfigs WHERE appId = ?', [ appId ]);
    return results;
}

async function getAppIdByValue(addonId, namePattern, value) {
    assert.strictEqual(typeof addonId, 'string');
    assert.strictEqual(typeof namePattern, 'string');
    assert.strictEqual(typeof value, 'string');

    const results = await database.query('SELECT appId FROM appAddonConfigs WHERE addonId = ? AND name LIKE ? AND value = ?', [ addonId, namePattern, value ]);
    if (results.length === 0) return null;
    return results[0].appId;
}

async function getByName(appId, addonId, namePattern) {
    assert.strictEqual(typeof appId, 'string');
    assert.strictEqual(typeof addonId, 'string');
    assert.strictEqual(typeof namePattern, 'string');

    const results = await database.query('SELECT value FROM appAddonConfigs WHERE appId = ? AND addonId = ? AND name LIKE ?', [ appId, addonId, namePattern ]);
    if (results.length === 0) return null;
    return results[0].value;
}

export default {
    get,
    set,
    unset,

    getByAppId,
    getByName,
    unsetByAppId,
    getAppIdByValue,
};
