module UserRewards
  class HypeTrainsController < UserRewards::BaseController
    def index
      authorize HypeTrain
    end

    def show
    end

    def grant_rewards
      authorize HypeTrain

      @participated_at_time = params[:hype_train][:participated_at]
      @time_zone = params[:hype_train][:time_zone]

      Time.zone = params[:hype_train][:time_zone]
      @participated_at = Time.zone.parse(params[:hype_train][:participated_at])

      track_action! trackable_request.assemble_an.admin_panel_hype_train_rewards_grant_query(
        channel_id: params[:hype_train][:channel_id],
        user_id: params[:hype_train][:user_id],
        timestamp: @participated_at
      )

      begin
        @hype_train, @granted_rewards, @user_owned_rewards, @participation_totals =
          HypeTrain.grant_rewards(params[:hype_train][:channel_id],
                                  params[:hype_train][:user_id],
                                  @participated_at)
      rescue StandardError => e
        flash[:error] = "Failed to grant user hype train rewards #{e.message}"
      ensure
        render "index"
      end
    end

    protected

    def hype_train_params
      params.require(:user_rewards_hype_train).permit(:channel_id, :user_id, :participated_at)
    end
  end
end
