// @flow

import { threadPermissions, threadTypes } from 'lib/types/thread-types';

import { dbQuery, SQL } from '../database/database';
import { endScript } from './utils';
import { recalculateAllThreadPermissions } from '../updaters/thread-permission-updaters';

async function main() {
  try {
    await addLeaveThreadPermissions();
    await recalculateAllThreadPermissions();
  } catch (e) {
    console.warn(e);
  } finally {
    endScript();
  }
}

async function addLeaveThreadPermissions() {
  const leaveThreadString = `$.${threadPermissions.LEAVE_THREAD}`;
  const updateAllRoles = SQL` 
    UPDATE roles r 
    LEFT JOIN threads t ON t.id = r.thread
    SET r.permissions = JSON_SET(permissions, ${leaveThreadString}, TRUE) 
    WHERE t.type != ${threadTypes.PERSONAL}
  `;
  await dbQuery(updateAllRoles);
}

main();

Create script to add LEAVE_THREAD permission
[server] Create script to add LEAVE_THREAD permission

Test Plan:
Tested on a single row to check if results are matching expectacions.
Inspected `membership` table to check if `leave_thread` permission is added. Inspected `roles` table to check if permission is added.
Ran a query after the script, and made sure only personal threads are in the result:
`SELECT * FROM roles WHERE JSON_EXTRACT(permissions, "$.leave_thread") IS NULL`
Checked if leave thread button is displayed and after pressing there are no errors and user leaves thread

Reviewers: ashoat, palys-swm

Reviewed By: ashoat

Subscribers: zrebcu411, Adrian

Differential Revision: https://phabricator.ashoat.com/D466
