class AnalysisReport < ApplicationRecord
  belongs_to :respondent_category
  has_one :insights_report, dependent: :destroy
  has_one :sections_report, dependent: :destroy
  has_one :themes_report, dependent: :destroy

  has_many :interview_questions, lambda { |report|
    where(id: report.question_ids)
  }, class_name: "InterviewQuestion", primary_key: :id, foreign_key: :id

  def respondents
    Respondent.where(id: respondent_ids)
  end

  def selected_sections
    MasterSection.where(id: section_ids)
  end

  def queue_report_generation!(sections_exist:, queue_insight_generation:, user_id:)
    if sections_exist
      SectionReportSummaryJob.perform_later(
        metadata: { sections_report_id: sections_report.id,
                    respondent_category_id: respondent_category.id,
                    is_all_data: false }, user_id:
      )
    end

    return unless queue_insight_generation

    InsightGenerationJob.perform_later(metadata: { insights_report_id: insights_report.id,
                                                   respondent_category_id: respondent_category.id,
                                                   is_all_data: false }, user_id:)
  end

  def self.queue_all_data_report_generation!(respondent_category_id:, queue_insight_generation:, sections_exist:, user_id:)
    if sections_exist
      SectionReportSummaryJob.perform_later(
        metadata: { respondent_category_id:, is_all_data: true },
        user_id:
      )
    end

    return unless queue_insight_generation

    InsightGenerationJob.perform_later(
      metadata: { respondent_category_id:, is_all_data: true },
      user_id:
    )
  end

  def generating?
    section_generating = SystemTask.where(
      task_type: %w[SectionReportSummary],
      running: true,
      status: %w[queued running]
    ).where(
      "metadata @> ?", { sections_report_id: sections_report.id, is_all_data: false }.to_json
    ).exists?

    insight_generating = SystemTask.where(
      task_type: %w[InsightGeneration InsightsReportSummary],
      running: true,
      status: %w[queued running]
    ).where(
      "metadata @> ?", { insights_report_id: insights_report.id, is_all_data: false }.to_json
    ).exists?

    insight_generating || section_generating
  end
end
