MAJOR=4
MINOR=34
DEVNAME=tty34
  F   ˆl–ßi~”Šj"Tâ‚Æ[¸ØÅ£�þ[}çq¹¡Œ€Òÿ?Î„ŸßÍ_�uÐb&=LyZËcõÃÌ ?÷     # Copyright (C) 2012-2026 Zammad Foundation, https://zammad-foundation.org/

# A reusable, credentialed handle to an AI provider endpoint; features can share one
# connection (see AI::FeatureProvider). Secrets in `config` are masked on serialization
# (CanMaskConfigSecrets), not encrypted at rest.
class AI::ProviderConnection < ApplicationModel
  include HasSearchIndexBackend
  include CanSelector
  include CanSearch
  include CanMaskConfigSecrets
  include ChecksClientNotification
  include HasAuditLogs

  # The purposes a connection can be the default for, each backed by a `for_<purpose>`
  # column. Keeps callers from deriving column names from unvalidated input.
  DEFAULT_PURPOSES = %w[chat embedding ocr].freeze

  # The two config values that describe the embedding model in numbers, with the message for a
  # value that is none. Each names the field as the dialog labels it, so an admin reading the
  # error knows which one to fix.
  EMBEDDING_METADATA_MESSAGES = {
    embedding_size:        __('The embedding dimensions must be a positive number.'),
    embedding_input_limit: __('The context window size must be a positive number.'),
  }.freeze

  # The search index gets the raw attributes (no masking hook), so `config` would ship the
  # provider token to Elasticsearch in plaintext. Neither column is searched: `status` is
  # machine state, and both are jsonb without a `flattened` mapping, which would additionally
  # let a type change of one config key reject the whole document.
  search_index_attributes_ignored :config, :status

  has_many :feature_providers,
           class_name: 'AI::FeatureProvider',
           inverse_of: :provider_connection,
           dependent:  :destroy

  validates :name,     presence: true, uniqueness: { case_sensitive: false }
  validates :provider, presence: true
  validate  :provider_must_be_known
  validate  :prevent_zammad_ai_provider_changes_on_saas
  validate  :embedding_model_present_when_serving_embeddings
  validate  :embedding_metadata_must_be_positive

  before_validation :drop_stale_embedding_default
  before_save       :remove_blank_config_values, :seed_recommended_embedding_model,
                    :remove_unconfigurable_embedding_model,
                    :remove_unsupported_embedding_default, :reset_status_on_config_change
  after_create   :ensure_default_chat, :seed_initial_optional_defaults, :enforce_optional_default_exclusivity
  after_update   :ensure_default_chat, :enforce_optional_default_exclusivity
  before_destroy :protect_online_service_connection
  after_destroy  :ensure_default_chat, :disable_ai_provider_without_connections
  # Every commit, not `on: %i[create update]`: the default maintenance above saves the record again
  # within the create's transaction, and a save that changes nothing replaces the trigger action the
  # `on:` filter matches - the callback would silently never run for a newly created connection. A
  # destroy needs no special case either: nothing serving embeddings reconciles to nothing.
  after_commit :reconcile_vector_index

  # Reentrancy guard for the default-maintenance callbacks' sibling saves (Ticket::State pattern).
  attr_accessor :callback_loop

  # Exposed only for the controller instance that performed this save, so its successful response
  # can tell the initiating admin about background work without persisting response state.
  attr_reader :vector_index_rebuild_started

  # Only an assigned connection receives calls, so only its stored status describes something the
  # admin can still act on; an unassigned one keeps its last result for the admin table alone.
  scope :in_use, lambda {
    where(default_chat: true)
      .or(where(default_embedding: true))
      .or(where(default_ocr: true))
      .or(where(id: AI::FeatureProvider.select(:provider_connection_id)))
  }

  def self.chat_connection
    all.detect(&:default_chat?)
  end

  def self.embedding_connection
    all.detect(&:default_embedding?)
  