# frozen_string_literal: true

class UxToolkitTextSnippetsController < ApplicationController
  layout 'admin'

  helper :sort
  include SortHelper

  before_action :require_admin
  before_action :find_snippet, only: [:edit, :update, :destroy, :enable, :disable]

  def index
    sort_init 'position', 'asc'
    sort_update 'title' => "#{UxToolkitTextSnippet.table_name}.title",
                'enabled' => "#{UxToolkitTextSnippet.table_name}.enabled",
                'updated_at' => "#{UxToolkitTextSnippet.table_name}.updated_at"

    @snippets = UxToolkitTextSnippet.reorder(sort_clause)
  end

  def new
    @snippet = UxToolkitTextSnippet.new(enabled: true, position: next_position)
  end

  def create
    @snippet = UxToolkitTextSnippet.new(snippet_params)

    if @snippet.save
      flash[:notice] = l(:notice_ux_toolkit_text_snippet_created)
      redirect_to ux_toolkit_text_snippets_path, status: :see_other
    else
      flash.now[:error] = snippet_error(@snippet, :error_ux_toolkit_text_snippet_create_failed)
      render :new, status: :unprocessable_entity
    end
  end

  def edit; end

  def update
    if @snippet.update(snippet_params)
      flash[:notice] = l(:notice_ux_toolkit_text_snippet_updated)
      redirect_to edit_ux_toolkit_text_snippet_path(@snippet)
    else
      flash.now[:error] = snippet_error(@snippet, :error_ux_toolkit_text_snippet_update_failed)
      render :edit, status: :unprocessable_entity
    end
  end

  def destroy
    if @snippet.destroy
      flash[:notice] = l(:notice_ux_toolkit_text_snippet_deleted)
    else
      flash[:error] = l(:error_ux_toolkit_text_snippet_delete_failed)
    end

    redirect_to ux_toolkit_text_snippets_path
  end

  def enable
    update_enabled(true, :notice_ux_toolkit_text_snippet_enabled)
  end

  def disable
    update_enabled(false, :notice_ux_toolkit_text_snippet_disabled)
  end

  private

  def find_snippet
    @snippet = UxToolkitTextSnippet.find(params[:id])
  rescue ActiveRecord::RecordNotFound
    render_404
  end

  def snippet_params
    params.require(:ux_toolkit_text_snippet).permit(
      :title,
      :snippet_text,
      :enabled,
      :position
    )
  end

  def next_position
    UxToolkitTextSnippet.maximum(:position).to_i + 1
  end

  def update_enabled(enabled, notice_key)
    if @snippet.update(enabled: enabled)
      flash[:notice] = l(notice_key)
    else
      flash[:error] = l(:error_ux_toolkit_text_snippet_update_failed)
    end

    redirect_back fallback_location: ux_toolkit_text_snippets_path
  end

  def snippet_error(snippet, fallback_key)
    snippet.errors.full_messages.to_sentence.presence || l(fallback_key)
  end
end
