module Twitch
  class TeamMembershipsController < ApplicationController
    before_action -> { authorize TeamMembership }
    before_action :set_team, only: :create
    before_action :set_channel, only: :create
    before_action :set_membership, only: :destroy

    def create
      membership = TeamMembership.new(membership_params)

      if membership.save
        flash[:success] = "Channel '#{@channel.login}' successfully added to team '#{@team.name}'!"
      else
        flash[:error] = membership.errors.full_messages
      end

      redirect_to twitch_team_members_path(@team)
    end

    def destroy
      if @membership.destroy
        flash[:notice] = "Membership for channel ID '#{@membership.channel_id}' and team ID '#{@membership.team_id}' has been deleted"
      else
        flash[:error] = @membership.errors.full_messages
      end

      redirect_back
    end

    private

    def membership_params
      params.require(:membership).permit(:revenue_revealed, :stats_revealed).merge(
        team_id: @team.id,
        channel_id: @channel.id.to_s
      )
    end

    def set_channel
      login = params.require(:channel_login).downcase
      @channel = User.find_by_login(login)

      if @channel.nil?
        flash[:error] = "Invalid channel: '#{login}' not found"
        redirect_to twitch_team_members_path(@team)
        return
      end

      if @channel.deleted_on || @channel.dmca_violation || @channel.terms_of_service_violation
        flash[:error] = "Invalid channel: '#{login}' not allowed"
        redirect_to twitch_team_members_path(@team)
        return
      end
    end

    def set_membership
      @membership = TeamMembership.find_by_slug(params[:slug])

      return true if @membership

      flash[:error] = 'Membership not found'
      redirect_back
    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
