class Admin::AdminController < ApplicationController

  layout 'admin'

  before_action :authenticate_user!
  before_action :only_admin!
  before_action :set_locale_to_default

  helper_method :current_user
  helper_method :user_signed_in?
  helper_method :form_locale, :available_locales

  # DELETE admin/cache/clear
  def clear_cache
    Rails.cache.clear

    respond_to do |format|
      format.turbo_stream { flash.now[:notice] = t(:cache_cleared, scope: 'utils') }
    end
  end

private


  def default_url_options
    { locale: I18n.locale }
  end


  def set_locale_to_default
    I18n.locale = I18n.default_locale
  end


  def form_locale
    (params['form_locale'] || I18n.locale).to_s
  end


  def available_locales
    @available_locales ||= I18n.available_locales.map(&:to_s).map(&:downcase).map{|v| v.sub('-', '_')}
  end


  def authenticate_user!
    unless user_signed_in?
      store_location
      redirect_to admin_sessions_path
    end
  end


  def only_admin!
    unless current_user&.admin_role?
      redirect_to root_path
    end
  end


  def current_user
    Current.user ||= authenticate_user_from_session
  end


  def authenticate_user_from_session
    User.enabled.find_by(id: session[:user_id])
  end


  def user_signed_in?
    current_user.present?
  end


  def login(user)
    Current.user = user
    reset_session
    user.touch(:last_logon_at)
    session[:user_id] = user.id
  end


  def logout(user)
    Current.user = nil
    reset_session
  end


  def redirect_back_or_default(default)
    redirect_to(session[:return_to] || default)
    session[:return_to] = nil
  end


  def store_location
    session[:return_to] = request.fullpath if request.get?
  end


end
