import type { ResultOf, VariablesOf } from '@inject/graphql/graphql'
import { SetEmailTodo } from '@inject/graphql/mutations.client'
import { GetEmailThread } from '@inject/graphql/queries'
import type { Client } from 'urql'

const instructorMarkTodo = async (client: Client, threadId: string) => {
  console.warn('marking todo!')
  const { data } = await client
    .query<ResultOf<typeof GetEmailThread>, VariablesOf<typeof GetEmailThread>>(
      GetEmailThread,
      {
        threadId,
      }
    )
    .toPromise()

  await Promise.all(
    (data?.emailThread.emails || [])
      .filter(x => !x.todo)
      .map(email =>
        client
          .mutation<unknown, VariablesOf<typeof SetEmailTodo>>(SetEmailTodo, {
            emailId: email.id,
            state: true,
          })
          .toPromise()
      )
  )
}

export default instructorMarkTodo
