'use strict';

const async = require('async');

function resolveRoleName(permissions = []) {
    if (permissions.length === 0) {
        return 'Viewer';
    }
    if (permissions.includes('ADMIN')) {
        return 'Admin';
    }
    return 'Editor';
}

exports.up = function(db, cb) {
    db.runSql(`SELECT id, permissions from users;`, (err, results) => {
        if (results.rowCount > 0) {
            const users = results.rows;
            const insertRootRole = users.map(u => {
                const roleName = resolveRoleName(u.permissions);
                return db.runSql.bind(
                    db,
                    `INSERT INTO role_user (role_id, user_id) 
                     SELECT id, '${u.id}'
                     FROM roles
                     WHERE name = '${roleName}' AND type = 'root';`,
                );
            });
            async.series(insertRootRole, cb);
        } else {
            cb();
        }
    });
};

exports.down = function(db, cb) {
    // We can't just remove roles for users as we don't know if there has been any manual additions.
    cb();
};

@@ -81,13 +81,8 @@
 ions
- = %5B%5D
 ) %7B%0A
@@ -81,32 +81,48 @@
 ions) %7B%0A    if (
+!permissions %7C%7C 
 permissions.leng
@@ -305,16 +305,25 @@
 .runSql(
+%0A        
 %60SELECT 
@@ -348,19 +348,75 @@
 om users
-;%60,
+ WHERE id NOT IN (select user_id from role_user);%60,%0A       
  (err, r
@@ -424,24 +424,28 @@
 sults) =%3E %7B%0A
+    
         if (
@@ -476,24 +476,28 @@
             
+   
+ 
 const users 
@@ -512,16 +512,20 @@
 s.rows;%0A
+    
         
@@ -580,24 +580,28 @@
             
+   
+ 
 const roleNa
@@ -649,24 +649,28 @@
             
+    
 return db.ru
@@ -704,12 +704,20 @@
     
-db,%0A
+    db,%0A    
     
@@ -934,19 +934,27 @@
         
+   
+ 
 );%0A
+    
         
@@ -961,16 +961,20 @@
     %7D);%0A
+    
         
@@ -1019,16 +1019,20 @@
         
+    
 %7D else %7B
@@ -1040,24 +1040,28 @@
             
+   
+ 
 cb();%0A      
@@ -1066,15 +1066,29 @@
     
-%7D%0A
     %7D
+%0A        %7D,%0A    
 );%0A%7D

migrate only users without any role