# frozen_string_literal: true

class UxToolkitChecklistTemplatesController < ApplicationController
  layout 'admin'

  before_action :require_login
  before_action :require_template_management
  before_action :find_template, only: [:edit, :update, :destroy]

  def index
    @templates = UxToolkitChecklistTemplate.ordered.includes(:items)
  end

  def new
    @template = UxToolkitChecklistTemplate.new(active: true)
  end

  def create
    @template = UxToolkitChecklistTemplate.new(template_params)

    if @template.save
      flash[:notice] = l(:notice_ux_toolkit_checklist_template_created)
      redirect_to edit_ux_toolkit_checklist_template_path(@template)
    else
      flash.now[:error] = template_error(@template, :error_ux_toolkit_checklist_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_checklist_template_updated)
      redirect_to edit_ux_toolkit_checklist_template_path(@template)
    else
      flash.now[:error] = template_error(@template, :error_ux_toolkit_checklist_template_update_failed)
      render :edit, status: :unprocessable_entity
    end
  end

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

    redirect_to ux_toolkit_checklist_templates_path
  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[:id])
  rescue ActiveRecord::RecordNotFound
    render_404
  end

  def template_params
    params.require(:ux_toolkit_checklist_template).permit(:name, :active)
  end

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