# frozen_string_literal: true

class UxToolkitChecklistTemplateItemsController < ApplicationController
  layout 'admin'

  before_action :require_login
  before_action :require_template_management
  before_action :find_template
  before_action :find_item, only: [:update, :destroy, :move_up, :move_down]

  def create
    @item = UxToolkitChecklistTemplateItem.new(item_params)
    @item.checklist_template = @template
    @item.position = UxToolkitChecklistTemplateItem.next_position_for(@template)

    if @item.save
      flash[:notice] = l(:notice_ux_toolkit_template_item_created)
    else
      flash[:error] = item_error(@item, :error_ux_toolkit_template_item_create_failed)
    end

    redirect_to edit_ux_toolkit_checklist_template_path(@template)
  end

  def update
    if @item.update(item_params)
      flash[:notice] = l(:notice_ux_toolkit_template_item_updated)
    else
      flash[:error] = item_error(@item, :error_ux_toolkit_template_item_update_failed)
    end

    redirect_to edit_ux_toolkit_checklist_template_path(@template)
  end

  def destroy
    if @item.destroy
      UxToolkitChecklistTemplateItem.normalize_positions_for(@template)
      flash[:notice] = l(:notice_ux_toolkit_template_item_deleted)
    else
      flash[:error] = l(:error_ux_toolkit_template_item_delete_failed)
    end

    redirect_to edit_ux_toolkit_checklist_template_path(@template)
  end

  def move_up
    move_item(:move_up)
  end

  def move_down
    move_item(:move_down)
  end

  private

  def require_template_management
    if !RedmineUxToolkit::Services::Checklists.enabled?
      flash[:error] = l(:error_ux_toolkit_checklist_templates_disabled)
      redirect_to plugin_settings_path(:redmine_ux_toolkit)
      return false
    end

    return true if RedmineUxToolkit::Services::Checklists.template_management_allowed?(User.current)

    render_403 message: :error_ux_toolkit_checklist_template_permission_denied
    false
  end

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

  def find_item
    @item = @template.items.find(params[:id])
  rescue ActiveRecord::RecordNotFound
    render_404
  end

  def item_params
    params.require(:ux_toolkit_checklist_template_item).permit(:subject)
  end

  def move_item(method_name)
    @item.public_send(method_name)
    UxToolkitChecklistTemplateItem.normalize_positions_for(@template)
    flash[:notice] = l(:notice_ux_toolkit_template_item_moved)
    redirect_to edit_ux_toolkit_checklist_template_path(@template)
  end

  def item_error(item, fallback_key)
    item.errors.full_messages.to_sentence.presence || l(fallback_key)
  end
end
