import { EmailSelection } from '@/analyst/utilities'
import type { EmailThread } from '@inject/graphql/fragment-types'

const getLastEmail = (
  emailThread: EmailThread,
  teamId: string,
  type: Omit<EmailSelection, 'drafts'>
) => {
  const index = emailThread.emails.findIndex(email => {
    switch (type) {
      case EmailSelection.RECEIVED: {
        return email.sender.team?.id !== teamId
      }
      case EmailSelection.SENT: {
        return email.sender.team?.id === teamId
      }
      default: {
        return true
      }
    }
  })
  if (index === -1) {
    return undefined
  }
  return emailThread.emails[index]
}

export default getLastEmail
