# frozen_string_literal: true

module RedmineUxToolkit
  module Services
    module TrackerChecklistTemplateInserter
      module_function

      def insert_for_issue(issue, user)
        return 0 unless Checklists.enabled?
        return 0 unless issue&.persisted? && issue.tracker_id.present?

        mapping = UxToolkitTrackerChecklistTemplate.for_tracker(issue.tracker_id).first
        template = mapping&.checklist_template
        return 0 unless template&.active? && template.items.exists?

        ChecklistTemplateCopier.new(issue: issue, template: template, user: user).copy!
      rescue StandardError => e
        Rails.logger.error(
          "[redmine_ux_toolkit] Automatic checklist insertion failed for issue " \
          "#{issue&.id}: #{e.class}: #{e.message}"
        )
        0
      end
    end
  end
end
