import { makeExecutableSchema } from '@graphql-tools/schema'
import Keys from '@inject/shared/localstorage/keys'
import subscribedTeamsQL from '../../schemas/subscribedTeams.graphql'
import type { Resolvers } from './subscribedTeamsType'
import type { Context, SubschemaConfig, SubschemaResolverType } from './typing'

const subscribedTeamSchema: SubschemaConfig = {
  merge: {
    TeamType: {
      fieldName: 'team',
      selectionSet: '{ id }',
      args: ({ id }) => ({ teamId: id }),
    },
  },
  schema: makeExecutableSchema<Context>({
    typeDefs: [subscribedTeamsQL],
    resolvers: {
      Query: {
        team: (_, { teamId }) => ({
          id: teamId,
          subscribed: JSON.parse(
            localStorage.getItem(Keys.getTeamSubscriptionKey(teamId)) || 'false'
          ) as boolean,
        }),
      },
      Mutation: {
        setSubscriptionTeam: (_, { teamId, state }) => {
          localStorage.setItem(
            Keys.getTeamSubscriptionKey(teamId),
            JSON.stringify(state)
          )
          return {
            id: teamId,
            subscribed: state,
          }
        },
      },
    } as SubschemaResolverType<Resolvers>,
  }),
}

export default subscribedTeamSchema
