import { IamRole } from '@api/graphql';
import { AccountPermissions } from '../iam-shared.types';

export const iamCreatePermissionsFromRoles = (roles: IamRole[]): AccountPermissions => {
  const accountPermissions: AccountPermissions = { all: [] };
  const allPermissions: string[] = [];

  for (const role of roles) {
    const rolePermissions: string[] = [];
    for (const permission of role.permissions ?? []) {
      if (!permission) continue;
      rolePermissions.push(permission.name);
      if (!allPermissions.includes(permission.name)) {
        allPermissions.push(permission.name);
      }
    }
    accountPermissions[role.id] = rolePermissions;
  }
  accountPermissions.all = allPermissions;

  return accountPermissions;
};
