import type {
  EmailAddressYaml,
  MappedEmailTemplateControl,
  MappedInjectControl,
  MappedMilestone,
  MappedQuestionnaireControl,
  MappedToolResponseControl,
  MilestoneYaml,
  ToolYaml,
} from '../types'

export const extractFirstMilestone = (activateMilestone?: string) =>
  activateMilestone?.split(',')[0].trim()

export const filterToolMilestones = (
  activityMilestones: MilestoneYaml[],
  tools: ToolYaml[]
) =>
  activityMilestones.filter((milestone: MilestoneYaml) =>
    tools.find((tool: ToolYaml) =>
      tool.responses.find(
        response =>
          extractFirstMilestone(response.control?.activate_milestone) ===
          milestone.name
      )
    )
  )

export const filterEmailMilestones = (
  activityMilestones: MilestoneYaml[],
  emails: EmailAddressYaml[]
) =>
  activityMilestones.filter((milestone: MilestoneYaml) =>
    emails.find((email: EmailAddressYaml) =>
      email.templates?.find(
        template =>
          extractFirstMilestone(template.control?.activate_milestone) ===
          milestone.name
      )
    )
  )

export const extractMilestonesFromControls = (
  toolControls: MappedToolResponseControl[],
  emailControls: MappedEmailTemplateControl[],
  injectControls: MappedInjectControl[],
  questionnaireControls: MappedQuestionnaireControl[]
) =>
  [
    ...toolControls.map(control => ({
      id: control.milestoneId,
      name: control.milestoneName,
    })),
    ...emailControls.map(control => ({
      id: control.milestoneId,
      name: control.milestoneName,
    })),
    ...injectControls.map(control => ({
      id: control.milestoneId,
      name: control.milestoneName,
    })),
    ...questionnaireControls.map(control => ({
      id: control.milestoneId,
      name: control.milestoneName,
    })),
  ].filter(
    control => control.id !== undefined && control.name !== undefined
  ) as MappedMilestone[]
