# frozen_string_literal: true

module RedmineUxToolkit
  module Services
    class RecentIssueTracker
      def self.track(user, issue, now: Time.current)
        new(user, issue, now).track
      rescue StandardError => e
        Rails.logger.warn("Redmine UX Toolkit recent issue tracking failed: #{e.class}: #{e.message}")
        nil
      end

      def initialize(user, issue, now)
        @user = user
        @issue = issue
        @now = now
      end

      def track
        return unless trackable?

        recent_issue = UxToolkitRecentIssue.find_or_initialize_by(
          user_id: user.id,
          issue_id: issue.id
        )
        recent_issue.last_visited_at = now
        recent_issue.save!

        trim_old_entries
        recent_issue
      end

      private

      attr_reader :user, :issue, :now

      def trackable?
        user&.logged? && issue.present? && issue.visible?(user)
      end

      def trim_old_entries
        limit = UxToolkitRecentIssue.configured_limit
        ids_to_keep = UxToolkitRecentIssue
                      .where(user_id: user.id)
                      .order(last_visited_at: :desc, id: :desc)
                      .limit(limit)
                      .pluck(:id)

        UxToolkitRecentIssue
          .where(user_id: user.id)
          .where.not(id: ids_to_keep)
          .delete_all
      end
    end
  end
end
