'use strict';

const crypto = require('node:crypto');

exports.up = async function (db) {
    const cmd = 'CREATE TABLE IF NOT EXISTS dockerRegistries(' +
        'id VARCHAR(128) NOT NULL UNIQUE,' +
        'provider VARCHAR(16) NOT NULL,' +
        'serverAddress VARCHAR(128) NOT NULL,' +
        'username VARCHAR(128),' +
        'email VARCHAR(128),' +
        'password VARCHAR(128),' +
        'PRIMARY KEY (id)) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin';

    await db.runSql(cmd);

    const result = await db.runSql('SELECT * FROM settings WHERE name=?', [ 'registry_config' ]);
    if (!result.length) return;

    await db.runSql('START TRANSACTION');
    const registryConfig = JSON.parse(result[0].value);

    if (registryConfig.provider !== 'noop') {
        await db.runSql('INSERT INTO dockerRegistries (id, provider, serverAddress, username, email, password) VALUES (?, ?, ?, ?, ?, ?)',
            [ `rc-${crypto.randomUUID()}`, registryConfig.provider, registryConfig.serverAddress, registryConfig.username, registryConfig.email || null, registryConfig.password ]);
    }

    await db.runSql('DELETE FROM settings WHERE name=?', [ 'registry_config']);
    await db.runSql('COMMIT');
};

exports.down = async function (db) {
    await db.runSql('DROP TABLE dockerRegistries');
};
