'use strict';

const USER_MANAGEMENT_PERMISSIONS = [
  'CREATE_USERS',
  'READ_USERS',
  'UPDATE_USERS',
  'DELETE_USERS',
  'READ_ROLES',
];

module.exports = {
  async up(queryInterface) {
    const sequelize = queryInterface.sequelize;
    const [roles] = await sequelize.query(
      `SELECT "id" FROM "roles" WHERE "name" = 'Administrator' LIMIT 1;`,
    );

    if (!roles.length) {
      return;
    }

    const [permissions] = await sequelize.query(
      `SELECT "id", "name" FROM "permissions" WHERE "name" IN (:permissionNames);`,
      {
        replacements: { permissionNames: USER_MANAGEMENT_PERMISSIONS },
      },
    );

    const now = new Date();

    for (const permission of permissions) {
      await sequelize.query(
        `INSERT INTO "rolesPermissionsPermissions" ("createdAt", "updatedAt", "roles_permissionsId", "permissionId")
         SELECT :createdAt, :updatedAt, :roleId, :permissionId
         WHERE NOT EXISTS (
           SELECT 1
           FROM "rolesPermissionsPermissions"
           WHERE "roles_permissionsId" = :roleId
             AND "permissionId" = :permissionId
         );`,
        {
          replacements: {
            createdAt: now,
            updatedAt: now,
            roleId: roles[0].id,
            permissionId: permission.id,
          },
        },
      );
    }
  },

  async down() {
    // Intentionally left blank. This protects live permission assignments.
  },
};
