# frozen_string_literal: true

class UxToolkitRecentIssue < ApplicationRecord
  DEFAULT_LIMIT = 10
  ALLOWED_LIMITS = [5, 10, 20].freeze

  belongs_to :user
  belongs_to :issue, optional: true

  validates :user_id, presence: true
  validates :issue_id, presence: true, uniqueness: {scope: :user_id}
  validates :last_visited_at, presence: true

  def self.visible_for(user)
    joins(:issue)
      .where(user_id: user.id)
      .merge(Issue.visible(user))
      .includes(issue: [:project, :status, :priority])
      .order(last_visited_at: :desc)
  end

  def self.configured_limit
    settings = Setting.plugin_redmine_ux_toolkit || {}
    limit = settings['recent_issues_limit'].to_i

    ALLOWED_LIMITS.include?(limit) ? limit : DEFAULT_LIMIT
  end
end
