class SessionsController < ApplicationController
  layout "authentication"
  allow_unauthenticated_access only: %i[ new create ]
  rate_limit to: 10, within: 3.minutes, only: :create, with: -> { redirect_to new_session_path, alert: "Try again later." }

  def new
    @show_oidc_login = oidc_configured?
    @oidc_provider_name = ENV['OIDC_PROVIDER_NAME'] || 'OpenID Connect'
    @show_registration = User.none?
  end

  def create
    if user = User.authenticate_by(params.permit(:email_address, :password))
      start_new_session_for user
      redirect_to after_authentication_url
    else
      redirect_to new_session_path, alert: "Try another email address or password."
    end
  end

  def destroy
    terminate_session
    redirect_to new_session_path, status: :see_other
  end

  private

  def oidc_configured?
    ENV['OIDC_DISCOVERY_URL'].present? &&
    ENV['OIDC_CLIENT_ID'].present? &&
    ENV['OIDC_CLIENT_SECRET'].present?
  end
end
