# frozen_string_literal: true

class UxToolkitChecklistTemplateInsertionsController < ApplicationController
  before_action :require_login
  before_action :find_visible_issue
  before_action :require_checklist_edit_permission
  before_action :find_template

  def create
    template_items = @template.items.ordered.to_a

    if template_items.empty?
      flash[:error] = l(:error_ux_toolkit_checklist_template_has_no_items)
      redirect_to issue_path(@issue)
      return
    end

    inserted_count = RedmineUxToolkit::Services::ChecklistTemplateCopier.new(
      issue: @issue,
      template: @template,
      user: User.current
    ).copy!
    flash[:notice] = l(:notice_ux_toolkit_checklist_template_inserted, count: inserted_count)
  rescue ActiveRecord::RecordInvalid
    flash[:error] = l(:error_ux_toolkit_checklist_template_insert_failed)
  ensure
    redirect_to issue_path(@issue) unless performed?
  end

  private

  def find_visible_issue
    @issue = Issue.visible(User.current).find(params[:issue_id])
    @project = @issue.project
  rescue ActiveRecord::RecordNotFound
    render_404
  end

  def require_checklist_edit_permission
    return if RedmineUxToolkit::Services::Checklists.edit_allowed?(@issue, User.current)

    flash[:error] = l(:error_ux_toolkit_checklist_permission_denied)
    redirect_to issue_path(@issue)
  end

  def find_template
    @template = UxToolkitChecklistTemplate.active.find(params[:template_id])
  rescue ActiveRecord::RecordNotFound
    flash[:error] = l(:error_ux_toolkit_checklist_template_not_available)
    redirect_to issue_path(@issue)
  end

end
