# frozen_string_literal: true

module RedmineUxToolkit
  module Services
    class ChecklistTemplateCopier
      def initialize(issue:, template:, user:)
        @issue = issue
        @template = template
        @user = user.presence
      end

      def copy!
        template_items = @template.items.ordered.to_a
        return 0 if template_items.empty?

        inserted_count = 0

        UxToolkitChecklistItem.transaction do
          next_position = UxToolkitChecklistItem.next_position_for(@issue)

          template_items.each do |template_item|
            UxToolkitChecklistItem.create!(
              issue: @issue,
              subject: template_item.subject,
              is_done: false,
              position: next_position,
              created_by: @user,
              updated_by: @user
            )
            next_position += 1
            inserted_count += 1
          end
        end

        inserted_count
      end
    end
  end
end
