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

function getLastEmail(
  emailThread: EmailThread,
  teamId: string,
  type: Omit<EmailSelection, 'drafts'>
) {
  const index = emailThread.emails.findIndex(email =>
    type === EmailSelection.RECEIVED
      ? email.sender.team?.id === teamId
      : email.sender.team?.id !== teamId
  )
  // this algorithm is still O(n) as the implementation in `useFilteredThreads, but it uses hit-first approach instead of filter-down
  return emailThread.emails.at(index === -1 ? 0 : index)
}

export default getLastEmail
