import { ApolloClient, InMemoryCache, createHttpLink, ApolloLink } from '@apollo/client/core'
import { provideApolloClient } from '@vue/apollo-composable'

export default defineNuxtPlugin((nuxtApp) => {
  const config = useRuntimeConfig()

  // Create HTTP links for each API
  const createLink = (uri: string) => createHttpLink({ uri })

  // Public Exchange API (no auth)
  const publicExchangeClient = new ApolloClient({
    link: createLink(config.public.exchangeGraphqlPublic as string),
    cache: new InMemoryCache(),
    defaultOptions: {
      watchQuery: { fetchPolicy: 'cache-and-network' },
      query: { fetchPolicy: 'network-only' },
    },
  })

  // Teams User API (ID Token)
  const teamsUserClient = new ApolloClient({
    link: createLink(config.public.teamsGraphqlUser as string),
    cache: new InMemoryCache(),
  })

  // Teams Team API (Access Token)
  const teamsTeamClient = new ApolloClient({
    link: createLink(config.public.teamsGraphqlTeam as string),
    cache: new InMemoryCache(),
  })

  // Exchange Team API (Access Token)
  const exchangeTeamClient = new ApolloClient({
    link: createLink(config.public.exchangeGraphqlTeam as string),
    cache: new InMemoryCache(),
  })

  // KYC Team API (Access Token)
  const kycTeamClient = new ApolloClient({
    link: createLink(config.public.kycGraphqlTeam as string),
    cache: new InMemoryCache(),
  })

  // Orders Team API (Access Token)
  const ordersTeamClient = new ApolloClient({
    link: createLink(config.public.ordersGraphqlTeam as string),
    cache: new InMemoryCache(),
  })

  // Provide default client
  provideApolloClient(publicExchangeClient)

  return {
    provide: {
      apollo: {
        publicExchange: publicExchangeClient,
        teamsUser: teamsUserClient,
        teamsTeam: teamsTeamClient,
        exchangeTeam: exchangeTeamClient,
        kycTeam: kycTeamClient,
        ordersTeam: ordersTeamClient,
      },
    },
  }
})
