module Twitch
  class TeamMembersController < ApplicationController
    before_action -> { authorize TeamMembership }
    before_action :set_team

    def index
      @memberships = TeamMembership.where(team_id: @team.id)
      @channel_map = map_ids_to_channels(@memberships.map(&:channel_id).uniq)
    end

    private

    def map_ids_to_channels(ids)
      channels = User.all(where: { id: ids }, per_page: ids.count)

      channels.each_with_object({}) { |channel, map| map[channel.id.to_s] = channel }
    end

    def set_team
      @team = Team.find_by_name(params[:team_name])

      return true if @team

      flash[:error] = "Team '#{params[:team_name]}' not found"
      redirect_to twitch_teams_path
    end
  end
end
