# frozen_string_literal: true

class UxToolkitTicketTemplatesController < ApplicationController
  layout 'admin'

  helper :sort
  include SortHelper

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

  def index
    sort_init 'position', 'asc'
    sort_update 'name' => "#{UxToolkitTicketTemplate.table_name}.name",
                'enabled' => "#{UxToolkitTicketTemplate.table_name}.enabled",
                'subject_template' => "#{UxToolkitTicketTemplate.table_name}.subject_template",
                'position' => "#{UxToolkitTicketTemplate.table_name}.position",
                'updated_at' => "#{UxToolkitTicketTemplate.table_name}.updated_at"

    @templates = UxToolkitTicketTemplate.reorder(sort_clause)
  end

  def new
    @template = UxToolkitTicketTemplate.new(enabled: true, position: next_position)
  end

  def create
    @template = UxToolkitTicketTemplate.new(template_params)

    if @template.save
      flash[:notice] = l(:notice_ux_toolkit_ticket_template_created)
      redirect_to ux_toolkit_ticket_templates_path, status: :see_other
    else
      flash.now[:error] = template_error(@template, :error_ux_toolkit_ticket_template_create_failed)
      render :new, status: :unprocessable_entity
    end
  end

  def edit; end

  def update
    if @template.update(template_params)
      flash[:notice] = l(:notice_ux_toolkit_ticket_template_updated)
      redirect_to edit_ux_toolkit_ticket_template_path(@template)
    else
      flash.now[:error] = template_error(@template, :error_ux_toolkit_ticket_template_update_failed)
      render :edit, status: :unprocessable_entity
    end
  end

  def destroy
    if @template.destroy
      flash[:notice] = l(:notice_ux_toolkit_ticket_template_deleted)
    else
      flash[:error] = l(:error_ux_toolkit_ticket_template_delete_failed)
    end

    redirect_to ux_toolkit_ticket_templates_path
  end

  def enable
    update_enabled(true, :notice_ux_toolkit_ticket_template_enabled)
  end

  def disable
    update_enabled(false, :notice_ux_toolkit_ticket_template_disabled)
  end

  private

  def find_template
    @template = UxToolkitTicketTemplate.find(params[:id])
  rescue ActiveRecord::RecordNotFound
    render_404
  end

  def template_params
    params.require(:ux_toolkit_ticket_template).permit(
      :name,
      :subject_template,
      :subject_template_mode,
      :description_template,
      :enabled,
      :position
    )
  end

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

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

    redirect_back fallback_location: ux_toolkit_ticket_templates_path
  end

  def template_error(template, fallback_key)
    template.errors.full_messages.to_sentence.presence || l(fallback_key)
  end
end
