import { useEventListener } from 'ahooks'
import { useTypedMutation } from '../graphql'
import { setIsUnreadEmailThread } from '../mutations.client'

const useEmailThreadSubscription = (
  teamId: string,
  selectedThreadId?: string
) => {
  const [, setIsUnread] = useTypedMutation(setIsUnreadEmailThread)

  useEventListener('actionLogEvent', e => {
    if (e.detail.actionLog.details.__typename === 'EmailType') {
      const newEmailThread = e.detail.actionLog.details.thread
      if (selectedThreadId !== newEmailThread.id) {
        setIsUnread({
          threadId: newEmailThread.id,
          teamId,
          isUnread: true,
        })
      }
    }
  })
}

export default useEmailThreadSubscription
