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 'TeamQuestionnaireStateType': {
      return actionLog.details.status === 'REVIEWED' || actionLog.details.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 'TeamQuestionnaireStateType':
      {
        const teamState = actionLog.details
        await client
          .mutation<unknown, VariablesOf<typeof SetTeamQuestionnaireTodo>>(
            SetTeamQuestionnaireTodo,
            {
              teamQuestionnaireId: teamState.id,
              state: !teamState.todo,
            }
          )
          .toPromise()
      }
      break
    default:
      await client
        .mutation<unknown, VariablesOf<typeof SetTodoActionLog>>(
          SetTodoActionLog,
          {
            actionLogId: actionLog.id,
            state: !actionLog.todo,
          }
        )
        .toPromise()
      break
  }
}
