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

const emailThreadsV0 = graphql(`
  query EmailThreadsV0(
    $teamId: ID!
    $received: Boolean = true
    $sent: Boolean = true
    $archived: Boolean = false
  ) {
    emailThreads(teamId: $teamId)
      @_filterEmails(received: $received, sent: $sent, archived: $archived) {
      id
      readReceipt {
        isUnread
        teamId
        threadId
      }
    }
  }
`)

/*
 * Counts amount of unopened emailthreads
 *
 * @params tab - counts unread threads for messages in respect to trainee tabs, for instructors the relation is flipped (received -> sent, sent -> received)
 */
function useGetEmailThreadUnreadCountSuspense(
  teamId: string,
  tab: 'received' | 'sent'
) {
  const [{ data }] = useTypedQuery({
    query: emailThreadsV0,
    variables: {
      teamId,
      received: tab === 'received',
      sent: tab === 'sent',
    },
  })
  return data?.emailThreads.filter(x =>
    x.readReceipt.find(x => x.teamId === teamId && x.isUnread)
  ).length
}

export default useGetEmailThreadUnreadCountSuspense
