# frozen_string_literal: true

module RedmineUxToolkit
  module Patches
    module IssuesControllerPatch
      def show
        super
        RedmineUxToolkit::Services::RecentIssueTracker.track(User.current, @issue)
      end

      def create
        issue_was_new = @issue&.new_record?
        super
        return unless issue_was_new && @issue&.persisted?

        unless params[:copy_from].present?
          RedmineUxToolkit::Services::TrackerChecklistTemplateInserter.insert_for_issue(@issue, User.current)
        end
        RedmineUxToolkit::Services::IssueAuthorWatcher.add_for_issue(@issue)
      end

      def update
        comment_notes = ux_toolkit_issue_notes_param
        super
        return unless ux_toolkit_real_comment?(comment_notes)
        return unless @issue&.persisted?

        journal = @issue.current_journal
        return if journal.nil? || journal.new_record?
        return unless ux_toolkit_real_comment?(journal.notes)

        RedmineUxToolkit::Services::IssueCommenterWatcher.add_for_issue(@issue, journal.user || User.current)
      end

      private

      def ux_toolkit_issue_notes_param
        issue_params = params[:issue]
        return nil unless issue_params.respond_to?(:[])

        issue_params[:notes]
      end

      def ux_toolkit_real_comment?(notes)
        notes.to_s.strip.present?
      end
    end
  end
end
