class Admin::DoorCodesController < ApplicationController
  before_action :ensure_admin

  def index
  end

  def new
  end

  def edit
  end

  def create
    if door_code.save
      flash[:notice] = "You have successfully created door code #{door_code.code}"
      redirect_to action: :index
    else
      flash[:warning] = "Errors saving code. See details below."
      render :new
    end
  end

  def update
    if door_code.update(door_code_params)
      flash[:notice] = "You have successfully updated door code #{door_code.code}"
      redirect_to action: :index
    else
      flash[:warning] = "Errors saving code. See details below."
      render :edit
    end
  end

  def generate_new
    num_codes_to_generate = 10
    num_codes_to_generate.times do
      DoorCode.create!(code: DoorCode.make_random_code)
    end

    flash[:notice] = "Autogenerated #{num_codes_to_generate} new codes (see table below for details)"
    redirect_to action: :index
  end

  private

  def door_code_params
    return {} unless params.key?(:door_code)

    params.require(:door_code).permit(:code, :index_number, :status, :user_id, :id)
  end

  helper_method def door_code
    @door_code ||= params.key?(:id) ? DoorCode.find(params[:id]) : DoorCode.new(door_code_params)
  end

  helper_method def door_codes
    @door_codes ||= DoorCode.all.includes(:user).order("users.name")
  end

  helper_method def door_codes_by_status
    @door_codes_by_status ||= door_codes.group_by(&:status)
  end
end
