export default defineNuxtRouteMiddleware(async () => {
  // Only run on client
  if (import.meta.server) return

  const { activeLogtoOrgId, setActiveTeam } = useActiveTeam()

  // Already loaded - skip
  if (activeLogtoOrgId.value) return

  const { loggedIn, getIdToken } = useAuth()

  // Not logged in - skip (auth-oidc will handle)
  if (!loggedIn.value) return

  try {
    const { $apollo } = useNuxtApp() as unknown as { $apollo: Record<string, any> }
    const client = $apollo.teamsUser
    const token = await getIdToken()

    if (!token) return

    const { GetMeDocument } = await import('~/composables/graphql/user/teams-generated')

    const result = await client.query({
      query: GetMeDocument,
      variables: {},
      context: { headers: { Authorization: `Bearer ${token}` } },
      fetchPolicy: 'network-only',
    })

    if (result.data?.me?.activeTeamId && result.data.me.activeTeam?.logtoOrgId) {
      setActiveTeam(result.data.me.activeTeamId, result.data.me.activeTeam.logtoOrgId)
    }
  } catch (err) {
    console.error('Failed to load active team in middleware:', err)
  }
})
