import { graphql, useTypedQuery } from '../graphql'

const emailThreadsV0 = graphql(`
  query EmailThreadsV0($teamId: ID!, $archived: Boolean = false) {
    emailThreads(teamId: $teamId) @_filterEmails(archived: $archived) {
      id
      emails {
        readReceipt
        sender {
          team {
            id
          }
        }
      }
    }
  }
`)

const useGetEmailThreadUnreadCountSuspense = (
  teamId: string,
  tab: 'received' | 'sent'
) => {
  const [{ data }] = useTypedQuery({
    query: emailThreadsV0,
    variables: {
      teamId,
    },
  })

  return data?.emailThreads.reduce(
    (prev, thread) =>
      prev +
      thread.emails.reduce((prev, email) => {
        if (tab === 'received' && email.sender.team?.id === teamId) {
          return prev
        }
        if (tab === 'sent' && email.sender.team?.id !== teamId) {
          return prev
        }
        return prev + (email.readReceipt ? 0 : 1)
      }, 0),
    0
  )
}

export default useGetEmailThreadUnreadCountSuspense
