# frozen_string_literal: true

# Project
class Project < ApplicationRecord
  has_many :tag_categories, dependent: :destroy
  has_many :tags, through: :tag_categories
  has_many :master_sections, dependent: :destroy
  belongs_to :organization
  has_many :respondent_categories, dependent: :destroy
  has_many :respondents, through: :respondent_categories
  has_many :interview_insights, through: :respondents
  has_many :section_summaries, as: :groupable, dependent: :destroy
  has_attached_file :image
  validates_attachment_content_type :image, content_type: %r{\Aimage/.*\z}

  def self.reset_all_assistants
    projects = Project.where.not(index_name: nil)
    projects.update!(index_name: nil)
    projects.each do |project|
      AssistantConversation.where(raggable: project).update!(outdated: true)
    end
  end

  def has_homogenous_language_subprojects
    categories = respondent_categories.includes(:respondents)

    # all categories must be homogenous first
    return false unless categories.all?(&:has_homogenous_language_respondents)

    # then ensure they share the same language
    languages = categories.map do |category|
      respondents = category.respondents
      respondents.map { |r| r.respondent_type == "transcript" ? r.manual_language : r.language }.compact.uniq.first
    end.compact

    languages.uniq.one?
  end

  def relevant_tag_categories
    TagCategory.where(project_id: [nil, id]).order(:created_at)
  end

  def relevant_master_sections
    MasterSection.where(project_id: [nil, id]).order(:name)
  end

  def signed_image_url
    SprintGCS.signed_url(
      bucket_name: "sprint-qualplatform",
      file_path: image.path
    )
  end

  def image_url
    if image_file_name.nil?
      Unsplash.random_image
    else
      image.url
    end
  end

  def random_sprint_color
    colors = ["#F44174", "#6153CC", "#E75121"]
    colors.sample
  end
end
