import {
  addEmailAddress,
  addEmailTemplate,
  getMilestoneByTypeAndReferenceId,
} from '@/editor/indexeddb/operations'
import { MilestoneEventType } from '@/editor/indexeddb/types'
import type {
  EmailAddressYaml,
  EmailTemplateYaml,
  MappedActivity,
} from '../types'
import { extractFirstMilestone } from './milestones'
import { getContentFile, getContentText } from './shared'

const loadEmailTemplates = async (
  emailAddressId: number,
  templates: EmailTemplateYaml[],
  activityMilestones: MappedActivity[]
) =>
  await Promise.all(
    templates.map(async template => {
      const file = await getContentFile(template.content)
      const content = await getContentText(template.content)
      const learningActivityId = activityMilestones.find(
        activity =>
          extractFirstMilestone(template.control?.activate_milestone) ===
          activity.milestoneName
      )?.id

      const id = await addEmailTemplate({
        emailAddressId,
        learningActivityId,
        context: template.context,
        content,
        fileId: file?.id,
      })
      const milestone = learningActivityId
        ? await getMilestoneByTypeAndReferenceId(
            MilestoneEventType.LEARNING_ACTIVITY,
            learningActivityId
          )
        : await getMilestoneByTypeAndReferenceId(MilestoneEventType.EMAIL, id)

      return {
        id,
        milestoneId: milestone?.id,
        milestoneName: extractFirstMilestone(
          template.control?.activate_milestone
        ),
      }
    })
  )

export const loadEmailAddresses = async (
  activityMilestones: MappedActivity[],
  addresses: EmailAddressYaml[]
) =>
  await Promise.all(
    addresses.map(async address => {
      const id = await addEmailAddress({
        address: address.address,
        teamVisible: address.team_visible,
        description: address.description,
        organization: address.organization,
      })
      return address.templates
        ? await loadEmailTemplates(id, address.templates, activityMilestones)
        : []
    })
  )
