import type LogtoClient from '@logto/node'
import { print } from 'graphql'

type SelectedLocation = {
  type: string
  uuid: string
  name: string
  latitude: number
  longitude: number
} | null

type MePayload = {
  id?: string | null
  firstName?: string | null
  lastName?: string | null
  phone?: string | null
  avatarId?: string | null
  activeTeamId?: string | null
  activeTeam?: {
    name?: string | null
    teamType?: string | null
    logtoOrgId?: string | null
    selectedLocation?: SelectedLocation
  } | null
  teams?: Array<{ id?: string | null; name?: string | null; logtoOrgId?: string | null; teamType?: string | null } | null> | null
} | null

export default defineEventHandler(async (event) => {
  if (event.context.meLoaded) return
  event.context.meLoaded = true

  const client = event.context.logtoClient as LogtoClient | undefined
  if (!client) return

  let idToken: string | null = null
  try {
    idToken = await client.getIdToken()
  } catch {
    return
  }

  if (!idToken) return

  try {
    const { GetMeDocument, GetMeProfileDocument } = await import('~/composables/graphql/user/teams-generated')
    const endpoint = process.env.NUXT_PUBLIC_TEAMS_GRAPHQL_USER || 'https://teams.optovia.ru/graphql/user/'

    const [meResponse, profileResponse] = await Promise.all([
      $fetch<{ data?: { me?: MePayload } }>(endpoint, {
        method: 'POST',
        headers: { Authorization: `Bearer ${idToken}` },
        body: { query: print(GetMeDocument) }
      }),
      $fetch<{ data?: { me?: MePayload } }>(endpoint, {
        method: 'POST',
        headers: { Authorization: `Bearer ${idToken}` },
        body: { query: print(GetMeProfileDocument) }
      })
    ])

    const baseMe = meResponse?.data?.me ?? null
    const profileMe = profileResponse?.data?.me ?? null
    if (baseMe || profileMe) {
      event.context.me = {
        ...(baseMe || {}),
        ...(profileMe || {}),
        activeTeam: baseMe?.activeTeam || profileMe?.activeTeam || null,
        teams: baseMe?.teams || null
      }
    }
  } catch {
    // Ignore if user context can't be fetched
  }
})
