namespace :zoom do
  desc "Setup necessary zoom roles and users"
  task :setup => :environment do
    zoom = Zoom.new

    # Find or create DirectME host role
    host_role = zoom.roles_list["roles"].select{ |r| r["name"] == ZoomGateway.HOST_ROLE }.first
    if host_role.present?
      Rails.logger.info "Role #{host_role["name"]} already present."
    else
      host_role = zoom.roles_create({
        name: ZoomGateway.HOST_ROLE,
        description: "Directme meetings host",
        privileges: %w(Role:Read)
      })
      Rails.logger.info "Created role #{ZoomGateway.HOST_ROLE}."
    end
  end


  desc "Synchronize ActiveRecord users with current account state"
  task :sync => :environment do
    zoom = Zoom.new

    roles = zoom.roles_list["roles"]
    ActiveRecord::Base.transaction do
      ZoomUser.tiers.keys.each do |tier|
        full_role_name = ZoomGateway.host_role_name(tier)
        role_id = roles.select { |r| r["name"] == full_role_name }.first["id"]
        user_ids = zoom.roles_members(role_id: role_id).dig("members").pluck("id")

        # Invalid db users (not existing on the given Zoom account, but existing in the app db)
        ZoomUser.current_account.public_send(tier).where.not(api_id: user_ids).each do |zu|
          zu.api_id = nil
          zu.destroy
        end

        # Missing zoom users (existing in given Zoom account, but not existing in the app db)
        (user_ids - ZoomUser.current_account.public_send(tier).pluck(:api_id)).each do |api_user_id|
          ZoomUser.current_account.public_send(tier).create(api_id: api_user_id)
        end
      end
    end
  end
end