module PayoutEntities
  class AttributionsController < PayoutEntities::BaseController
    def destroy
      authorize PayoutEntity

      options = {ldap_login: current_user.ldap_login}

      response = Attribution.remove_attribution(params[:payout_entity_id], params[:channel_id], options)

      if response.success?
        flash[:success] = "Successfully removed user #{params[:channel_id]} from #{params[:payout_entity_id]} "
      else
        flash[:error] = "#{response.body['message']}. Attribution could not be removed."
      end

      redirect_back
    end

    def create
      authorize PayoutEntity

      options = {ldap_login: current_user.ldap_login}

      @user = Twitch::User.find_by_login(params[:login])
      if @user.blank?
        flash[:error] = "User #{params[:login]} not found"
        return redirect_back
      end

      response = Attribution.add_attribution(params[:payout_entity_id], @user.id, params[:start_date], options)

      if response.success?
        flash[:success] = "Successfully added #{params[:login]} to #{params[:payout_entity_id]} "
      else
        flash[:error] = "#{response.body['message']}. Attribution could not be added."
      end

      redirect_back
    end
  end
end
