/* jslint node:true */

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

const CERT_PREFIX = 'cert';
const CERT_SUFFIX = 'cert';


const BLOBS_FIELDS = [ 'id', 'value' ].join(',');

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

    const result = await database.query(`SELECT ${BLOBS_FIELDS} FROM blobs WHERE id = ?`, [ id ]);
    if (result.length === 0) return null;
    return result[0].value;
}

async function getString(id) {
    assert.strictEqual(typeof id, 'string');

    const result = await database.query(`SELECT ${BLOBS_FIELDS} FROM blobs WHERE id = ?`, [ id ]);
    if (result.length === 0) return null;
    return result[0].value.toString('utf8');
}

async function set(id, value) {
    assert.strictEqual(typeof id, 'string');
    assert(value === null || Buffer.isBuffer(value));

    await database.query('INSERT INTO blobs (id, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value=VALUES(value)', [ id, value ]);
}

async function setString(id, value) {
    assert.strictEqual(typeof id, 'string');
    assert(value === null || typeof value === 'string');

    await database.query('INSERT INTO blobs (id, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value=VALUES(value)', [ id, Buffer.from(value) ]);
}

async function del(id) {
    await database.query('DELETE FROM blobs WHERE id=?', [ id ]);
}

async function clear() {
    await database.query('DELETE FROM blobs');
}

async function listCertIds() {
    const result = await database.query('SELECT id FROM blobs WHERE id LIKE ?', [ `${CERT_PREFIX}-%.${CERT_SUFFIX}` ]);
    return result.map(r => r.id);
}

export default {
    get,
    getString,
    set,
    setString,
    del,

    listCertIds,

    ACME_ACCOUNT_KEY: 'acme_account_key',
    ADDON_TURN_SECRET: 'addon_turn_secret',

    // the code relies on sftp_<keytype>_* pattern
    SFTP_RSA_PUBLIC_KEY: 'sftp_rsa_public_key',
    SFTP_RSA_PRIVATE_KEY: 'sftp_rsa_private_key',
    SFTP_ED25519_PUBLIC_KEY: 'sftp_ed25519_public_key',
    SFTP_ED25519_PRIVATE_KEY: 'sftp_ed25519_private_key',

    PROXY_AUTH_TOKEN_SECRET: 'proxy_auth_token_secret',

    OIDC_KEY_EDDSA: 'oidc_key_eddsa', // this is only JWT private key, the public key will be derived
    OIDC_KEY_RS256: 'oidc_key_rs256',

    CERT_PREFIX,
    CERT_SUFFIX,
    _clear: clear
};
