module Subscriptions
  class TokensController < Subscriptions::BaseController

    AUDIT_ACTION_UPDATE = "update"
    AUDIT_TOKEN_PRODUCT = "token_product"
    AUDIT_LDAP_USER = "ldap_user"

    def index
      authorize Token
      return if params[:subscriptions_tokens].blank?

      form = params[:subscriptions_tokens]
      user_login = form[:userLogin]
      user_id = form[:userID]

      @user = if user_id.present?
                Twitch::User.find(user_id)
              elsif user_login.present?
                Twitch::User.find_by_login(user_login)
              end
      if @user.nil?
        flash[:error] = "Cannot find user"
        return
      end

      params = {}
      params[:purchaser_id] = @user.id
      @purchase_orders = Payments::PurchaseOrder.filter(params)

      @token_balance = Token.get_token_balance(@user.id)
      @token_history = self.get_token_history(@user.id)
    end

    def grant_tokens
      authorize Token

      user_id = params[:user_id]
      user_login = params[:user_login]
      form = params[:subscriptions_tokens]
      quantity = form[:quantity]

      new_fields = {
        quantity: form[:quantity],
      }

      current_balance = Token.get_token_balance(user_id)
      old_fields = {
        quantity: current_balance
      }

      if quantity.to_i > 10
        flash[:error] = "Can only grant a maximum number of 10 token"
      else
        success = Token.grant_tokens_for_user(user_id, quantity)
        if !success
          flash[:error] = "Error granting tokens to user"
        else
          audit_token_product(old_fields, new_fields)
          @token_balance = Token.get_token_balance(user_id)
          flash[:success] = "Successfully granted #{quantity} tokens for #{user_login}. Please refresh if the token balance isn't reflected immediately"
        end
      end
      redirect_back
    end

    def get_token_history(user_id)
      authorize Token
      authorize Payments::Transaction
      @transactions = Payments::Transaction.transactions_for_user(user_id)
    end

    protected

    def audit_token_product(prev_token_product_params, curr_token_product_params)
      changes = []

      curr_token_product_params.each do |key, _|
        symbol = key.to_sym
        change = History::ChangeSet.new(
          attribute: symbol,
          old_value: prev_token_product_params[symbol],
          new_value: curr_token_product_params[symbol]
        )
        changes.push(change)
      end

      audit = History::Audit.new(
        action: AUDIT_ACTION_UPDATE,
        user_type: AUDIT_LDAP_USER,
        user_id: current_user.ldap_login,
        resource_type: AUDIT_TOKEN_PRODUCT,
        resource_id: curr_token_product_params[:id],
        changes: changes
      )

      History::AddAudit.add(audit)
    end
  end
end
