import { getQuestionnaires } from '@/editor/indexeddb/joins'
import type {
  JoinedQuestionnaireInject,
  QuestionnaireQuestion,
} from '@/editor/indexeddb/types'
import notEmpty from '@inject/shared/utils/notEmpty'
import { isEmpty, pickBy } from 'lodash'
import { generateContent, generateControl, generateOverlay } from './shared'

const generateQuestionnaireQuestions = async (
  questionnaireQuestions: QuestionnaireQuestion[]
) =>
  await Promise.all(
    questionnaireQuestions.map(async questionnaireQuestion =>
      pickBy({
        content: await generateContent(
          `qq_${questionnaireQuestion.id}`,
          questionnaireQuestion.text
        ),
        max: questionnaireQuestion.max,
        correct: questionnaireQuestion.correct,
        labels: questionnaireQuestion.labels,
      })
    )
  )

export const generateQuestionnaires = async () => {
  const questionnaires = await getQuestionnaires()

  const generatedQuestionnaires = await Promise.all(
    questionnaires
      .filter(notEmpty)
      .map(async (questionnaire: JoinedQuestionnaireInject) =>
        pickBy({
          title: questionnaire.title,
          time: questionnaire.injectControl?.start,
          control: generateControl(
            questionnaire.activateMilestone,
            questionnaire.milestoneCondition
          ),
          overlay: generateOverlay(questionnaire.overlay),
          questions: await generateQuestionnaireQuestions(
            questionnaire.questions
          ),
        })
      )
  )

  return isEmpty(generatedQuestionnaires) ? undefined : generatedQuestionnaires
}
