# frozen_string_literal: true

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

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

      def track
        return unless trackable?

        recent_project = UxToolkitRecentProject.find_or_initialize_by(
          user_id: user.id,
          project_id: project.id
        )
        recent_project.last_visited_at = now
        recent_project.save!

        trim_old_entries
        recent_project
      end

      private

      attr_reader :user, :project, :now

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

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

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