# frozen_string_literal: true

module RedmineUxToolkit
  module Services
    module IssueCloseGuards
      module_function

      def prevent_closing_with_open_subtasks_enabled?
        settings = Setting.plugin_redmine_ux_toolkit || {}
        settings.fetch('prevent_closing_with_open_subtasks', '0').to_s == '1'
      end

      def open_subtask_count_for(issue)
        return 0 unless issue&.persisted?

        Issue.joins(:status)
             .where(parent_id: issue.id)
             .where(issue_statuses: {is_closed: false})
             .count
      rescue ActiveRecord::StatementInvalid => e
        Rails.logger.warn("[redmine_ux_toolkit] Could not count open subtasks: #{e.class.name}")
        0
      end

      def subtask_closing_blocked_hint?(issue)
        prevent_closing_with_open_subtasks_enabled? &&
          issue.present? &&
          !RedmineUxToolkit::Compatibility.issue_closed?(issue.status) &&
          open_subtask_count_for(issue).positive?
      end
    end
  end
end
