# frozen_string_literal: true

class SettingsController < ApplicationController
  before_action :require_authentication
  before_action :authorize_settings_management

  # GET /settings
  def index
    @settings = Setting.all.index_by(&:key)
  end

  # PATCH /settings
  def update
    setting_key = params[:key]
    setting_value = params[:value]

    if setting_key.present?
      Setting.set(setting_key, setting_value)
      redirect_to settings_path, notice: 'Setting was successfully updated.'
    else
      redirect_to settings_path, alert: 'Invalid setting key.'
    end
  end

  private

  def authorize_settings_management
    # Only allow admins to manage settings
    redirect_to root_path, alert: 'Access denied' unless Current.user&.admin?
  end
end
