module Subscriptions
  class ResubTokensController < Subscriptions::BaseController
    def index
      authorize Substwirp::ResubTokens

      return if params[:resub_token].blank?

      form = params[:resub_token]
      channel_id = form[:channelID]
      channel_login = form[:channelName]
      user_id = form[:userID]
      user_login = form[:userName]

      channel = if channel_id.present?
                  Twitch::User.find(channel_id)
                elsif channel_login.present?
                  Twitch::User.find_by_login(channel_login)
                end

      user =  if user_id.present?
                Twitch::User.find(user_id)
              elsif user_login.present?
                Twitch::User.find_by_login(user_login)
              end

      if channel.blank?
        flash[:error] = "No channel found for: #{channel_id || channel_login}"
        return redirect_to(subscriptions_tenures_path)
      end

      if user.blank?
        flash[:error] = "No user found for: #{user_id || user_login}"
        return redirect_to(subscriptions_tenures_path)
      end

      channel_id = channel.id.to_s
      user_id = user.id.to_s

      token_resp = Substwirp::ResubTokens.get_available_token(user_id, channel_id)
      @has_token = !token_resp.chat_notification_token.blank?

      @used_token_history = Substwirp::ResubTokens.get_all_used_tokens(user_id, channel_id)
      @owner_id = user_id
      @channel_id = channel_id

      track_action! trackable_request
        .assemble_an
        .admin_panel_resub_tokens_search(
          user_login:    form[:userName],
          channel_login: form[:channelName],
          user_id:       form[:userID],
          channel_id:    form[:channelID]
        )
    end

    def allow_replay
      authorize Substwirp::ResubTokens

      Substwirp::ResubTokens.allow_replay(params[:owner_id], params[:channel_id], params[:tenure])

      redirect_back
    end
  end
end
