import { InMemoryCache } from '@apollo/client'
import type { StrictTypedTypePolicies } from './apollo-helpers'
import { sanitizeHtmlCustom } from './sanitize'

const typePolicies: StrictTypedTypePolicies = {
  Query: {
    fields: {
      exerciseId: {
        read(_, { args, toReference }) {
          return toReference({
            __typename: 'ExerciseType',
            id: args?.exerciseId || '',
          })
        },
      },
      actionLog: {
        read(_, { args, toReference }) {
          return toReference({
            __typename: 'ActionLogType',
            id: args?.logId || '',
          })
        },
      },
      definition: {
        read(_, { args, toReference }) {
          return toReference({
            __typename: 'DefinitionType',
            id: args?.definitionId || '',
          })
        },
      },
      emailThread: {
        read(_, { args, toReference }) {
          return toReference({
            __typename: 'EmailThreadType',
            id: args?.threadId || '',
          })
        },
      },
      user: {
        read(_, { args, toReference }) {
          return toReference({
            __typename: 'UserType',
            id: args?.userId || '',
          })
        },
      },
      team: {
        read(_, { args, toReference }) {
          return toReference({
            __typename: 'TeamType',
            id: args?.teamId || '',
          })
        },
      },
      questionnaireState: {
        read(_, { args, toReference }) {
          return toReference({
            __typename: 'TeamQuestionnaireStateType',
            team: toReference({
              __typename: 'TeamType',
              id: args?.teamId || '',
            }),
            questionnaire: toReference({
              __typename: 'QuestionnaireType',
              id: args?.questionnaireId || '',
            }),
          })
        },
      },
      channel: {
        read(_, { args, toReference }) {
          return toReference({
            __typename: 'DefinitionChannelType',
            id: args?.channelId || '',
          })
        },
      },
    },
  },
  ActionLogType: {
    keyFields: ['id'],
  },
  ContentType: {
    fields: {
      rendered: {
        read(data) {
          return sanitizeHtmlCustom(data)
        },
      },
    },
  },
  EmailThreadType: {
    keyFields: ['id'],
  },
  EmailType: {
    keyFields: ['id'],
  },
  ExerciseType: {
    keyFields: ['id'],
    fields: {
      definition: {
        merge: true,
      },
    },
  },
  EmailTemplateType: {
    keyFields: ['id'],
  },
  MilestoneType: {
    keyFields: ['id'],
  },
  TeamType: {
    keyFields: ['id'],
    fields: {
      exercise: {
        merge: true,
      },
    },
  },
  TeamQuestionnaireStateType: {
    keyFields: ['team', 'questionnaire'],
  },
  DefinitionChannelType: {
    keyFields: ['id'],
  },
}

const cache = new InMemoryCache({
  typePolicies,
})

export default cache
