class ApplicationController < ActionController::Base
  rescue_from DeviseLdapAuthenticatable::LdapException do |exception|
    render :text => exception, :status => 500
  end

  before_action :sentry_set_user

  def sentry_set_user
    return unless Setting.sentry_enabled

    if user_signed_in?
      Sentry.set_user(id: current_user.id, username: current_user.cn)
    else
      Sentry.set_user({})
    end
  end

  def require_user_signed_in
    unless user_signed_in?
      redirect_to welcome_path and return
    end
  end

  def require_user_signed_out
    if user_signed_in?
      redirect_to root_path and return
    end
  end

  def authorize_admin
    http_status :forbidden unless current_user.is_admin?
  end

  def http_status(status)
    respond_to do |format|
      format.html { render template: "shared/status_#{status.to_s}", status: status }
      format.any  { head status }
    end
  end

  def after_sign_in_path_for(user)
    session[:user_return_to] || root_path
  end

  def lndhub_authenticate(options={})
    if session[:ln_auth_token].present? && !options[:force_reauth]
      @ln_auth_token = session[:ln_auth_token]
    else
      lndhub = Lndhub.new
      auth_token = lndhub.authenticate(current_user)
      session[:ln_auth_token] = auth_token
      @ln_auth_token = auth_token
    end
  rescue => e
    Sentry.capture_exception(e) if Setting.sentry_enabled?
  end

  def lndhub_fetch_balance
    @balance = LndhubManager::FetchUserBalance.call(auth_token: @ln_auth_token)
  rescue AuthError
    lndhub_authenticate(force_reauth: true)
    raise if @fetch_balance_retried
    @fetch_balance_retried = true
    lndhub_fetch_balance
  end

  def nostr_event_from_params
    params.permit!
    params[:signed_event].to_h.symbolize_keys
  end
end
