# frozen_string_literal: true

module RedmineUxToolkit
  module Services
    class IssueAuthorWatcher
      class << self
        def add_for_issue(issue)
          return unless auto_watch_issue_author_enabled?
          return unless issue&.persisted?

          author = issue.author
          return unless author.is_a?(User) && author.active?
          return if issue.watched_by?(author)
          return unless author.allowed_to?(:add_issue_watchers, issue.project)
          return unless RedmineUxToolkit::Compatibility.valid_watcher?(issue, author)

          RedmineUxToolkit::Compatibility.add_watcher(issue, author)
        rescue StandardError => e
          Rails.logger.warn(
            "[redmine_ux_toolkit] Could not add issue author as watcher for issue #{issue&.id}: " \
            "#{e.class}: #{e.message}"
          )
        end

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