# frozen_string_literal: true

class AdminNotice < ActiveRecord::Base
  TRANSLATION_KEY_DETAIL = "_translation_key"
  MESSAGE_ALLOWED_TAGS = %w[a pre ul li].freeze
  MESSAGE_ALLOWED_ATTRIBUTES =
    (%w[href target rel] + SiteSettings::LabelFormatter::LINK_ATTRIBUTES).freeze
  MESSAGE_SANITIZER = Rails::Html::SafeListSanitizer.new

  validates :identifier, presence: true

  enum :priority, %i[low high].freeze
  enum :subject, %i[problem].freeze

  def message
    translation_data = details.symbolize_keys
    translation_key =
      translation_data.delete(TRANSLATION_KEY_DETAIL.to_sym) || "dashboard.#{subject}.#{identifier}"

    translated = I18n.t(translation_key, **translation_data.merge(base_path: Discourse.base_path))

    MESSAGE_SANITIZER.sanitize(
      SiteSettings::LabelFormatter.expand_setting_links(translated),
      tags: MESSAGE_ALLOWED_TAGS,
      attributes: MESSAGE_ALLOWED_ATTRIBUTES,
    )
  end
end

# == Schema Information
#
# Table name: admin_notices
#
#  id         :bigint           not null, primary key
#  details    :json             not null
#  identifier :string           not null
#  priority   :integer          not null
#  subject    :integer          not null
#  created_at :datetime         not null
#  updated_at :datetime         not null
#
# Indexes
#
#  index_admin_notices_on_identifier  (identifier)
#  index_admin_notices_on_subject     (subject)
#
