# frozen_string_literal: true

class NewPermissionSystem < ActiveRecord::DataMigration
  def up
    say 'Creating AccountAuths and ProjectMemberships for existing Projects...'

    User.all.each do |user|
      next if user.account_id_old.nil?

      role = user.role_old == 0 ? :associate : :account_manager
      account = Account.find(user.account_id_old)

      # Create a membership to the account for the user
      AccountAuth.create(user: user, account: account, role: role)

      # If the user is not an account manager, create a membership to each project in the account for the user
      if role != :account_manager
        account.projects.each do |project|
          ProjectMembership.create!(project: project, user: user)
        end
      end
    end

    say 'Done.'
  end

  def down
    say 'Destroying new permission system artifacts'
    ProjectMembership.destroy_all
    AccountAuth.destroy_all
    say 'Done.'
  end
end
