class Admin::UsersController < Admin::BaseController
  before_action :set_user, except: [:index]
  before_action :set_current_section

  # GET /admin/users
  def index
    ldap   = LdapService.new
    @ou    = Setting.primary_domain
    @pagy, @users = pagy(User.where(ou: @ou).order(cn: :asc))

    @stats = {
      users_confirmed: User.where(ou: @ou).confirmed.count,
      users_pending: User.where(ou: @ou).pending.count
    }
  end

  # GET /admin/users/:username
  def show
    if Setting.lndhub_admin_enabled?
      @lndhub_user = @user.lndhub_user
    end

    @services_enabled = @user.services_enabled

    @avatar = LdapManager::FetchAvatar.call(cn: @user.cn)
  end

  # POST /admin/users/:username/invitations
  def create_invitations
    amount = params[:amount].to_i
    notify_user = ActiveRecord::Type::Boolean.new.cast(params[:notify_user])

    CreateInvitations.call(user: @user, amount: amount, notify: notify_user)

    redirect_to admin_user_path(@user.cn), flash: {
      success: "Added #{amount} invitations to #{@user.cn}'s account"
    }
  end

  # DELETE /admin/users/:username/invitations
  def delete_invitations
    invitations = @user.invitations.unused
    amount = invitations.count

    invitations.destroy_all

    redirect_to admin_user_path(@user.cn), flash: {
      success: "Removed #{amount} invitations from #{@user.cn}'s account"
    }
  end

  private

  def set_user
    @user = User.find_by(cn: params[:username], ou: Setting.primary_domain)
    http_status :not_found unless @user
  end

  def set_current_section
    @current_section = :users
  end
end
