class CloseReasonsController < ApplicationController
  before_action :verify_moderator
  before_action :check_create_access, only: [:new, :create]
  before_action :set_close_reason, only: [:edit, :update]
  before_action :verify_admin_for_global_reasons, only: [:edit, :update]

  def index
    @close_reasons = if current_user.global_admin? && params[:global] == '1'
                       CloseReason.unscoped.where(community_id: nil)
                     else
                       CloseReason.unscoped.where(community_id: @community.id)
                     end
  end

  def edit; end

  def update
    before = @close_reason.attributes.map { |k, v| "#{k}: #{v}" }.join(' ')
    if @close_reason.update(close_reason_params)
      after = @close_reason.attributes.map { |k, v| "#{k}: #{v}" }.join(' ')

      AuditLog.moderator_audit(event_type: 'close_reason_update',
                               related: @close_reason,
                               user: current_user,
                               comment: "from <<CloseReason #{before}>>\nto <<CloseReason #{after}>>")

      if @close_reason.community.nil?
        redirect_to close_reasons_path(global: 1)
      else
        redirect_to close_reasons_path
      end
    else
      render :edit, status: :bad_request
    end
  end

  def new
    @close_reason = CloseReason.new(community: params[:global] == '1' ? nil : @community)
  end

  def create
    community_params = { community: params[:global] == '1' ? nil : @community }
    @close_reason = CloseReason.new(close_reason_params.merge(community_params))

    if @close_reason.save
      attr = @close_reason.attributes_print

      AuditLog.moderator_audit(event_type: 'close_reason_create',
                               related: @close_reason,
                               user: current_user,
                               comment: "<<CloseReason #{attr}>>")

      if @close_reason.community.nil?
        redirect_to close_reasons_path(global: 1)
      else
        redirect_to close_reasons_path
      end
    else
      render :new, status: :bad_request
    end
  end

  private

  def close_reason_params
    params.require(:close_reason).permit(:name, :description, :requires_other_post, :active)
  end

  def set_close_reason
    @close_reason = CloseReason.unscoped.find(params[:id])
  end

  def check_create_access
    not_found! unless current_user&.global_admin? || params[:global] != '1'
  end

  def verify_admin_for_global_reasons
    if !current_user.global_admin? && @close_reason.community.nil?
      not_found!
    end
  end
end
