module Twitch
  class ImpersonatesController < Twitch::BaseController
    before_action :set_user
    before_action :validate_params

    def create
      imp = Passport::UserImpersonation.new(
        user_id: params[:user_id],
        ticket_id: params[:ticket_id],
        reason: params[:reason],
        user_ip: request.remote_ip,
        admin_id: current_user.ldap_login
      )
      imp.audit_impersonation
      redirect_to imp.url

      track_action! trackable_request
        .assemble_an
        .admin_panel_user_impersonate(
          user_id: params[:user_id],
          reason: params[:reason],
          reference: params[:ticket_id].presence
        )
    end

    private

    def set_user
      @user = User.find params[:user_id]

      if @user.blank?
        flash[:error] = "User not found"
        return redirect_to twitch_users_path
      end

      authorize @user, :impersonate_user?
    end

    def validate_params
      if params[:reason].blank?
        flash[:error] = 'Reason is required for impersonation'
        return redirect_to @user
      end

      too_long = [
        :reason,
        :ticket_id
      ].select { |key| params[key] && params[key].length > 1024 }
      unless too_long.empty?
        flash[:error] = "Parameters are too long: #{too_long.join(', ')}"
        return redirect_to @user
      end
    end
  end
end
