import assert from 'node:assert';
import BoxError from './boxerror.js';
import database from './database.js';
import safe from 'safetydance';

const MAIL_PASSWORD_FIELDS = [ 'clientId', 'userId', 'password', 'creationTime' ].join(',');

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

    const result = await database.query('SELECT ' + MAIL_PASSWORD_FIELDS + ' FROM mailPasswords WHERE clientId = ? AND userId = ?', [ clientId, userId ]);
    if (result.length === 0) return null;
    return result[0];
}

async function getByUserId(userId) {
    assert.strictEqual(typeof userId, 'string');

    return await database.query('SELECT ' + MAIL_PASSWORD_FIELDS + ' FROM mailPasswords WHERE userId = ?', [ userId ]);
}

async function add(clientId, userId, password) {
    assert.strictEqual(typeof clientId, 'string');
    assert.strictEqual(typeof userId, 'string');
    assert.strictEqual(typeof password, 'string');

    if (clientId.length < 1) throw new BoxError(BoxError.BAD_FIELD, 'clientId must be at least 1 char');
    if (userId.length < 1) throw new BoxError(BoxError.BAD_FIELD, 'userId must be at least 1 char');
    if (password.length < 1) throw new BoxError(BoxError.BAD_FIELD, 'password must be at least 1 char');

    const query = 'INSERT INTO mailPasswords (clientId, userId, password) VALUES (?, ?, ?)';
    const args = [ clientId, userId, password ];

    const [error] = await safe(database.query(query, args));
    if (error && error.sqlCode === 'ER_DUP_ENTRY') throw new BoxError(BoxError.ALREADY_EXISTS, 'mail password for this app and user already exists');
    if (error && error.sqlCode === 'ER_NO_REFERENCED_ROW_2') throw new BoxError(BoxError.NOT_FOUND, 'app or user not found');
    if (error) throw error;

    return { clientId, userId };
}

async function list(userId) {
    assert.strictEqual(typeof userId, 'string');

    return await database.query('SELECT ' + MAIL_PASSWORD_FIELDS + ' FROM mailPasswords WHERE userId = ? ORDER BY clientId', [ userId ]);
}

async function delByClientId(clientId) {
    assert.strictEqual(typeof clientId, 'string');

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

export default {
    get,
    getByUserId,
    add,
    list,
    delByClientId,
};
