class Assistant < ApplicationRecord
  belongs_to :organization

  has_many :assistant_scopes, dependent: :destroy
  has_many :assistant_conversations, dependent: :destroy

  # Convenience associations to fetch specific scope types
  has_many :projects, through: :assistant_scopes, source: :scopable, source_type: "Project"
  has_many :respondent_categories, through: :assistant_scopes, source: :scopable, source_type: "RespondentCategory"

  before_validation :generate_index_name, on: :create

  # Gathers all unique respondents from both Projects and Categories
  def respondents
    project_respondent_ids = Respondent.joins(respondent_category: :project)
                                       .where(projects: { id: projects.select(:id) })
                                       .pluck(:id)

    category_respondent_ids = Respondent.where(respondent_category_id: respondent_categories.select(:id))
                                        .pluck(:id)

    all_ids = (project_respondent_ids + category_respondent_ids).uniq
    Respondent.where(id: all_ids)
  end

  def dominant_language
    scoped_respondents = respondents

    # 1. If any respondent in the entire mixed scope needs translation, default to English
    return "en" if scoped_respondents.where(translate: true).exists?

    # 2. Extract the actual language based on the respondent type for all respondents
    languages = scoped_respondents.map do |r|
      r.respondent_type == "transcript" ? r.manual_language : r.language
    end.compact.uniq

    # 3. If there is exactly one language across all scopes, use it. Otherwise, default to English.
    if languages.one?
      scoped_respondents.first&.transcript_language || "en"
    else
      "en"
    end
  end

  private

  def generate_index_name
    self.index_name ||= SecureRandom.hex(24)
  end
end
