class Admin::SessionsController < Admin::AdminController

  layout 'sessions'

  skip_before_action :authenticate_user!, except: %i[destroy]
  skip_before_action :only_admin!

  def index
    render action: 'new'
  end


  def create
    if user = User.enabled.authenticate_by(params.permit(:email, :password))
      # login user
      # redirect_back_or_default(admin_root_path(locale: I18n.default_locale))

      session[:verify_user_id] = user.id
      UserMailer.with(user: user, verification_code: user.verification_codes.create).verify_email.deliver_later

      redirect_to action: 'verification', locale: nil

    else
      flash.now.alert = t :'sessions.login_failed'
      render action: 'new', status: :unprocessable_entity
    end
  end


  def destroy
    logout current_user
    redirect_to root_path
  end


  # GET
  def verification

  end


  # POST
  def verify
    if params[:verification_code] =~ /\A\d{6}\z/ and
      user = User.enabled.find(session[:verify_user_id]) and
      user.verification_codes.valid.find_by(token: params[:verification_code])

      login user
      redirect_back_or_default(admin_root_path(locale: I18n.default_locale))
    else
      flash.now.alert = t :'sessions.verification_failed'
      render "verification"
    end
  end

end
