# frozen_string_literal: true

class Users::SessionsController < Devise::SessionsController
  # before_action :configure_sign_in_params, only: [:create]

  # GET /resource/sign_in
  def new
    session[:shared_secret] = SecureRandom.base64(12)
    super
  end

  # POST /resource/sign_in
  # def create
  #   super
  # end

  # DELETE /resource/sign_out
  # def destroy
  #   super
  # end

  # POST /users/nostr_login
  def nostr_login
    signed_event = Nostr::Event.new(**nostr_event_from_params)

    is_valid_sig  = signed_event.verify_signature
    is_valid_auth = NostrManager::VerifyAuth.call(
      event: signed_event,
      challenge: session[:shared_secret]
    )

    session[:shared_secret] = nil

    unless is_valid_sig && is_valid_auth
      flash[:alert] = "Login verification failed"
      http_status :unauthorized and return
    end

    user = LdapManager::FetchUserByNostrKey.call(pubkey: signed_event.pubkey)

    if user.present?
      set_flash_message!(:notice, :signed_in)
      sign_in("user", user)
      render json: { redirect_url: after_sign_in_path_for(user) }, status: :ok
    else
      flash[:alert] = "Failed to find your account. Nostr login may be disabled."
      http_status :unauthorized
    end
  end

  protected

    def set_flash_message(key, kind, options = {})
      # Hide flash message after redirecting from a signin route while logged in
      super unless key == :alert && kind == "already_authenticated"
    end

  # If you have extra params to permit, append them to the sanitizer.
  # def configure_sign_in_params
  #   devise_parameter_sanitizer.permit(:sign_in, keys: [:attribute])
  # end
end
