module PayoutEntities
  class ActivationsController < PayoutEntities::BaseController
    before_action :set_user, only: [:new]

    def new
      @activation = Activation.new
      authorize @activation
    end

    def index
      authorize PayoutEntity

      options = {ldap_login: current_user.ldap_login}

      response = Activation.find_all(options)

      if response.success?
        @activations = response.body
        if @activations.present?
          @activations.each do |a|
            a["login"] = Twitch::User.find(a["channel_id"]).login
          end
        end
      elsif response.body["message"]
        flash[:error] = response.body["message"]
        redirect_back
      end
    end

    def create
      @activation = Activation.new activation_params
      authorize @activation

      options = {ldap_login: current_user.ldap_login}
      if @activation.activate(options)
        flash[:success] = "Successfully activated #{@activation.channel_name} for custom partnership!"
        redirect_to payout_entities_activations_path
      else
        flash[:error] = @activation.errors.full_messages.to_sentence
        redirect_back
      end
    end

    protected

    def activation_params
      params.require(:payout_entities_activation)
    end
  end
end
