# Copyright (C) 2012-2026 Zammad Foundation, https://zammad-foundation.org/

class KnowledgeBase < ApplicationModel
  include HasTranslations
  include HasAgentAllowedParams
  include ChecksKbClientNotification
  include TriggersKnowledgeBaseContentUpdates

  AGENT_ALLOWED_NESTED_RELATIONS = %i[translations].freeze

  LAYOUTS = %w[grid list].freeze

  # How one list of content is ordered when browsed: by hand (`acts_as_list` positions, which is
  # what every installation had before this existed and what content predating it kept), by title
  # in the browsed locale, or most recently updated first.
  #
  # Stored per list rather than per node, so a category orders its subcategories and its answers
  # independently (`category_sorting_mode` / `answer_sorting_mode`) — an editor can keep the
  # subcategories alphabetical while arranging the answers by hand. The knowledge base root lists
  # categories only and therefore carries the category mode alone, under the same name.
  SORTING_MODES = %w[manual alphabetical last_update].freeze

  # What a list sorts by before anyone chooses: new content is ordered by title, not by the
  # creation sequence a `manual` list would fall back to with no hand-made order behind it.
  #
  # The knowledge base root takes it from the column default, so every create path fills it without
  # asking — `InitializeKnowledgeBase` on a fresh install, `KnowledgeBaseSortingMode` on an upgraded
  # one, where it takes over from the `manual` those columns are backfilled with. A category reads
  # this constant itself, for the one list it has nothing above it to inherit from (see
  # KnowledgeBase::Category#inherit_sorting_modes) — so the two have to agree, and a fresh record
  # compared against this in the model specs is what pins them together.
  DEFAULT_SORTING_MODE = 'alphabetical'.freeze

  # Folder icon of each supported icon set: the default a new category starts with (see
  # #default_category_icon) and what every existing category is reset to whenever the icon set is
  # switched (see #reset_category_icons). Kept in sync with
  # `App.KnowledgeBaseCategory.defaultIconFor`, which supplies the same defaults to newly created
  # categories in the legacy frontend.
  ICONSET_DEFAULT_CATEGORY_ICONS = {
    'FontAwesome'       => 'f115',
    'anticon'           => 'e662',
    'material'          => 'e94d',
    'ionicons'          => 'f139',
    'Simple-Line-Icons' => 'e039',
  }.freeze

  ICONSETS = ICONSET_DEFAULT_CATEGORY_ICONS.keys.freeze

  has_many                      :kb_locales, class_name: 'KnowledgeBase::Locale',
                                             inverse_of: :knowledge_base,
                                             dependent:  :destroy

  accepts_nested_attributes_for :kb_locales, allow_destroy: true
  validates                     :kb_locales, presence: true
  validates                     :kb_locales, length: { maximum: 1, message: __('System supports only one locale for knowledge base. Upgrade your plan to use more locales.') }, unless: :multi_lingual_support?

  has_many :categories, class_name: 'KnowledgeBase::Category',
                        inverse_of: :knowledge_base,
                        dependent:  :restrict_with_exception

  has_many :answers, through: :categories

  has_many :permissions, class_name: 'KnowledgeBase::Permission',
                         as:         :permissionable,
                         autosave:   true,
                         dependent:  :destroy

  validates :category_layout, inclusion: { in: KnowledgeBase::LAYOUTS }
  validates :homepage_layout, inclusion: { in: KnowledgeBase::LAYOUTS }

  validates :color_highlight,   presence: true, 'validations/color': true
  validates :color_header,      presence: true, 'validations/color': true
  validates :color_header_link, presence: true, 'validations/color': true

  validates :iconset, inclusion: { in: KnowledgeBase::ICONSETS }

  validates :category_sorting_mode, inclusion: { in: KnowledgeBase::SORTING_MODES }

  validate :validate_custom_address

  before_validation :patch_custom_address

  after_create  :set_defaults
  after_update  :reset_category_icons, if: :saved_change_to_iconset?
  after_destroy :set_kb_active_setting
  after_save    :set_kb_active_setting

  include KnowledgeBase::HasAuditLogs

  scope :active, -> { where(active: true) }

  alias assets_essential assets

  def assets(data)
    return data if assets_added_to?(data)

    data = super
    ApplicationModel::CanAssets.reduce(kb_locales + translations, data)
  end

  # assets without unnecessary bits
  def assets_public(data)
    data = assets_essential(data)

    data[:KnowledgeBase].each_value do |elem|
      elem.delete_if do |k, _|
        k.end_with?('_ids')
      end
    end

    data
  end

  def custom_address_uri
    return nil if custom_address.blank?

    scheme = Setting.get('http_type') || 'http'

    URI("#{scheme}://#{custom_address}")
  rescue URI::InvalidURIError
    nil
  end

  def custom_address_matches?(request)
    uri = custom_address_uri

    return false if uri.blank?

    given_fqdn = request.headers.env['SERVER_NAME']&.downcase
    given_path = request.headers.env['HTTP_X_ORIGINAL_URL']&.downcase

    # original url header not present, server not configured
    return false if given_path.nil?

    # path doesn't match
    return false if uri.path.downcase != given_path[0, uri.path.length]

    # domain present, but doesn't match
    return false if uri.host.present? && uri.host.downcase != given_fqdn

    true
  rescue URI::InvalidURIError
    false
  end

  def custom_address_prefix(request)
    host        = custom_address_uri.host.presence || request.headers.env['SERVER_NAME']
    port        = request.headers.env['SERVER_PORT']
    port_silent = (request.ssl? && port == '443') || (!request.ssl? && port == '80')
    port_string = port_silent ? '' : ":#{port}"

    "#{custom_address_uri.scheme}://#{host}#{port_string}"
  end

  def custom_address_path(path)
    uri = custom_address_uri

    return path if !uri

    custom_path  = custom_address_uri.path || ''
    applied_path = path.gsub(%r{^/help}, custom_path)

    applied_path.presence || '/'
  end

  def canonical_host
    custom_address_uri&.host.presence || Setting.get('fqdn')
  end

  def canonical_scheme_host
    "#{Setting.get('http_type')}://#{canonical_host}"
  end

  def canonical_url(path)
    "#{canonical_scheme_host}#{custom_address_path(path)}"
  end

  def full_destroy!
    ChecksKbClientNotification.disable_in_all_classes!

    audit_log_name

    transaction do
      # suppress audit log entries of the cascade, the destroy entry
      # of the knowledge base itself is sufficient
      AuditLog.suspend do
        # get all categories with their children, deepest first, to delete children before parents
        all_children
          .reorder(KnowledgeBase::Category.recursive_tree_depth_column => :desc)
          .each(&:full_destroy!)
        translations.each(&:destroy!)
        kb_locales.each(&:destroy!)

        # reset the association so the dependent destroy of the knowledge base
        # does not run the callbacks of the destroyed locales a second time
        kb_locales.reset
      end

      # `destroy!`'s `dependent: :restrict_with_exception` check on `categories` reads whatever is
      # already cached on the association, not a fresh query — without resetting it here, a caller
      # that touched `categories` earlier (even just `.count`) would see a stale non-empty cache and
      # `destroy!` would wrongly raise, even though every category was just destroyed above.
      categories.reset
      destroy!
    end
  ensure
    ChecksKbClientNotification.enable_in_all_classes!
  end

  # Returns all of this knowledge base's categories via a single recursive CTE instead of one
  # query per tree level. Each row also carries the CTE's depth and `recursive_tree_path` columns
  # (an array of category ids from root down to and including itself) — no custom SELECT needed,
  # which keeps the relation aggregatable (e.g. `.count`).
  def all_children
    KnowledgeBase::Category.with_recursive_tree_cte(direction: :down, seed: categories.root)
  end

  def visible?
    active?
  end

  def api_url
    Rails.application.routes.url_helpers.knowledge_base_path(self)
  end

  def load_category(locale, id)
    categories.localed(locale).find_by(id: id)
  end

  def self.with_multiple_locales_exists?
    KnowledgeBase
      .active
      .joins(:kb_locales)
      .group('knowledge_bases.id')
      .pluck(Arel.sql('COUNT(knowledge_base_locales.id) as locales_count'))
      .any? { |e| e > 1 }
  end

  def permissions_effective
    cache_key = KnowledgeBase::Permission.cache_key self

    Rails.cache.fetch cache_key do
      permissions
    end
  end

  def attributes_with_association_ids
    attrs = super
    attrs[:permissions_effective] = permissions_effective
    attrs
  end

  def self.granular_permissions?
    KnowledgeBase::Permission.any?
  end

  def self.access_for_user(user)
    hash = {
      granular: KnowledgeBase.granular_permissions?,
      editor:   user&.permissions?('knowledge_base.editor'),
      reader:   user&.permissions?('knowledge_base.reader')
    }

    case hash
    in { granular: true, reader: true } | { granular: true, editor: true }
      :granular
    in { editor: true }
      :editor
    in { reader: true }
      :reader
    else
      :public
    end
  end

  def public_content?(kb_locale = nil)
    scope = answers.published

    scope = scope.localed(kb_locale.system_locale) if kb_locale

    scope.any?
  end

  # Icon a category of this knowledge base starts out with, before the user picks their own.
  def default_category_icon
    ICONSET_DEFAULT_CATEGORY_ICONS[iconset]
  end

  private

  def set_defaults
    self.translations = kb_locales.map do |kb_locale|
      name      = Setting.get('organization').presence || Setting.get('product_name').presence || 'Zammad'
      kb_suffix = ::Translation.translate kb_locale.system_locale.locale, 'Knowledge Base'

      KnowledgeBase::Translation.new(
        title:       "#{name} #{kb_suffix}",
        footer_note: "© #{name}",
        kb_locale:   kb_locale
      )
    end
  end

  def validate_custom_address
    return if custom_address.nil?

    # not domain, but no leading slash
    if custom_address.exclude?('.') && custom_address[0] != '/'
      errors.add(:custom_address, __('must begin with a slash ("/")'))
    end

    if custom_address.include?('://')
      errors.add(:custom_address, __('must not include a protocol (e.g., "http://" or "https://")'))
    end

    if custom_address.last == '/'
      errors.add(:custom_address, __('must not end with a slash ("/")'))
    end

    if custom_address == '/' # rubocop:disable Style/GuardClause
      errors.add(:custom_address, __('must be a valid path or domain'))
    end
  end

  def patch_custom_address
    self.custom_address = nil if custom_address == ''
  end

  def multi_lingual_support?
    Setting.get 'kb_multi_lingual_support'
  end

  def set_kb_active_setting
    Setting.set 'kb_active', KnowledgeBase.active.exists?
    CanBePublished.update_active_publicly!
  end

  # A category stores its icon as a bare glyph codepoint of the knowledge base's icon set, so after
  # a switch every one of them points into the new font — where the same codepoint is usually
  # unmapped (blank glyph) or, worse, mapped to an entirely unrelated icon. The sets share no
  # meaningful icon-to-icon mapping, so the icons cannot be carried over; resetting them all to the
  # new set's folder icon at least keeps the knowledge base rendering, at the price of the previous
  # (now unrepresentable) choices. Admins are warned about that beforehand in the admin interface.
  #
  # Updates record by record on purpose: `update_all` would skip the client notifications and
  # content-update pings open sessions need to pick up the new icons.
  def reset_category_icons
    default_icon = ICONSET_DEFAULT_CATEGORY_ICONS[iconset]

    categories.find_each do |category|
      category.category_icon = default_icon

      # The icon comes from the validated `iconset`, so there is nothing to validate here — while
      # validating would drag in every unrelated rule the category and its translations have. A
      # single category left invalid by an import or a validation bypass would then make the icon set
      # unswitchable, of all things by aborting the very update which repairs the broken rendering.
      category.save!(validate: false)
    end
  end
end
