class ApplicationController < ActionController::Base
  helper_method :anonymous_session_id, :current_role, :current_user, :online_agents_count, :controller_namespace
  after_action :update_last_seen_at, if: :user_signed_in?
  before_action :set_locale, :authenticate_via_http_basic_auth
  before_action do
    ActiveStorage::Current.url_options = {
      host: request.base_url
    }
  end

  protected

  def authenticate_role!(*roles)
    if !user_signed_in?
      redirect_to new_user_session_path
    elsif !current_user.role.to_sym.in?(roles)
      head :forbidden
    end
  end

  private

  def update_flash_messages_turbo_stream
    turbo_stream.replace(:flash_messages, partial: "layouts/flash_messages")
  end

  def set_locale
    I18n.locale = current_user&.locale || session[:locale] || I18n.default_locale
    session[:locale] = I18n.locale
  end

  def update_last_seen_at
    current_user.touch(:last_seen_at)
  end

  def current_role
    current_user&.role&.to_sym
  end

  def anonymous_session_id
    cookies.encrypted["client_id"] ||= SecureRandom.hex(3)
  end

  def after_sign_in_path_for(user)
    agent_service_requests_path if user.role == "agent"

    root_path
  end

  def online_agents_count
    User.online_agents_count
  end

  def controller_namespace
    self.class.module_parent.to_s.downcase.to_sym
  end

  def authenticate_via_http_basic_auth
    return if Rails.env.development? || Rails.env.test?

    authenticate_or_request_with_http_basic do |name, password|
      name == "warteraum" &&
        password == Rails.application.credentials.dig(:staging, :http_auth)
    end
  end
end
