import type {
  ActionLogFlat,
  SimplifiedActionLog,
} from '@inject/graphql/fragment-types'
import type { VariablesOf } from '@inject/graphql/graphql'
import {
  SetEmailTodo,
  SetTeamQuestionnaireTodo,
  SetTodoActionLog,
} from '@inject/graphql/mutations.client'
import type { Client } from 'urql'

export const selectTodoCat = (
  actionLog: SimplifiedActionLog | ActionLogFlat
) => {
  switch (actionLog.details.__typename) {
    case 'EmailType':
      return actionLog.details.todo
    case 'QuestionnaireType': {
      const teamState = actionLog.details.teamQuestionnaireStates.find(
        x => x.team.id === actionLog.team.id
      )
      if (!teamState) {
        throw Error("Couldn't find TeamState, invariant failed")
      }
      return teamState.todo
    }
    default:
      return actionLog.todo
  }
}

export const execTodoWrite = async (
  client: Client,
  actionLog: SimplifiedActionLog | ActionLogFlat
) => {
  switch (actionLog.details.__typename) {
    case 'EmailType':
      await client
        .mutation<unknown, VariablesOf<typeof SetEmailTodo>>(SetEmailTodo, {
          emailId: actionLog.details.id,
          state: !actionLog.details.todo,
        })
        .toPromise()
      break
    case 'QuestionnaireType':
      {
        const teamState = actionLog.details.teamQuestionnaireStates.find(
          x => x.team.id === actionLog.team.id
        )
        if (!teamState) {
          throw Error("Couldn't find TeamState, invariant failed")
        }
        await client
          .mutation<unknown, VariablesOf<typeof SetTeamQuestionnaireTodo>>(
            SetTeamQuestionnaireTodo,
            {
              questionnaireId: teamState.questionnaire.id,
              teamId: teamState.team.id,
              state: !teamState.todo,
            }
          )
          .toPromise()
      }
      break
    default:
      await client
        .mutation<unknown, VariablesOf<typeof SetTodoActionLog>>(
          SetTodoActionLog,
          {
            actionLogId: actionLog.id,
            state: !actionLog.todo,
          }
        )
        .toPromise()
      break
  }
}
