import { getEmailAddresses } from '@/editor/indexeddb/joins'
import {
  type JoinedEmailAddress,
  type JoinedEmailTemplate,
} from '@/editor/indexeddb/types'
import { isEmpty, pickBy } from 'lodash'
import { generateContent, generateControl } from './shared'

const generateTemplates = async (emailTemplates: JoinedEmailTemplate[]) => {
  const generatedTemplates = await Promise.all(
    emailTemplates.map(async emailTemplate =>
      pickBy({
        context: emailTemplate.context,
        content: await generateContent(
          `et_${emailTemplate.id}`,
          emailTemplate.content,
          emailTemplate.file
        ),
        control: generateControl(emailTemplate.activateMilestone),
      })
    )
  )

  return isEmpty(generatedTemplates) ? undefined : generatedTemplates
}

export const generateEmailAddresses = async () => {
  const emailAddresses = await getEmailAddresses()

  const generatedAddresses = await Promise.all(
    emailAddresses.map(async (emailAddress: JoinedEmailAddress) =>
      pickBy({
        address: emailAddress.address,
        team_visible: emailAddress.teamVisible,
        description: emailAddress.description,
        organization: emailAddress.organization,
        templates: await generateTemplates(emailAddress.emailTemplates),
      })
    )
  )

  return isEmpty(generatedAddresses) ? undefined : generatedAddresses
}
