'use strict';

const async = require('async'),
    fs = require('node:fs'),
    path = require('node:path');

const AVATAR_DIR = '/home/yellowtent/boxdata/profileicons';

exports.up = function(db, callback) {
    db.runSql('ALTER TABLE users ADD COLUMN avatar MEDIUMBLOB', function (error) {
        if (error) return callback(error);

        fs.readdir(AVATAR_DIR, function (error, filenames) {
            if (error && error.code === 'ENOENT') return callback();
            if (error) return callback(error);

            async.eachSeries(filenames, function (filename, iteratorCallback) {
                const avatar = fs.readFileSync(path.join(AVATAR_DIR, filename));
                const userId = filename;

                db.runSql('UPDATE users SET avatar=? WHERE id=?', [ avatar, userId ], iteratorCallback);
            }, function (error) {
                if (error) return callback(error);

                fs.rm(AVATAR_DIR, { recursive: true }, callback);
            });
        });
    });
};

exports.down = function(db, callback) {
    db.runSql('ALTER TABLE users DROP COLUMN avatar', function (error) {
        if (error) console.error(error);
        callback(error);
    });
};

