const AUTH_KEY = '_auth'

// Platform ellenőrzés - csak kliens oldalon
const isNative = (): boolean => {
  if (typeof window === 'undefined') return false
  try {
    const { Capacitor } = require('@capacitor/core')
    return Capacitor.isNativePlatform()
  } catch {
    return false
  }
}

export const useAuthToken = () => {
  const token = ref<string | null>(null)
  const isLoaded = ref(false)

  // Token betöltése
  const loadToken = async (): Promise<string | null> => {
    // SSR esetén ne csináljunk semmit
    if (typeof window === 'undefined') {
      return null
    }

    if (isNative()) {
      // Natív app: Preferences használata
      const { Preferences } = await import('@capacitor/preferences')
      const { value } = await Preferences.get({ key: AUTH_KEY })
      token.value = value
    } else {
      // Web: Cookie használata
      const cookie = useCookie(AUTH_KEY)
      token.value = cookie.value || null
    }
    isLoaded.value = true
    return token.value
  }

  // Token mentése
  const setToken = async (newToken: string): Promise<void> => {
    if (typeof window === 'undefined') return

    token.value = newToken
    if (isNative()) {
      const { Preferences } = await import('@capacitor/preferences')
      await Preferences.set({ key: AUTH_KEY, value: newToken })
    } else {
      const cookie = useCookie(AUTH_KEY, { maxAge: 60 * 60 * 24 * 365 }) // 1 év
      cookie.value = newToken
    }
  }

  // Token törlése (kijelentkezés)
  const clearToken = async (): Promise<void> => {
    if (typeof window === 'undefined') return

    token.value = null
    if (isNative()) {
      const { Preferences } = await import('@capacitor/preferences')
      await Preferences.remove({ key: AUTH_KEY })
    } else {
      const cookie = useCookie(AUTH_KEY)
      cookie.value = null
    }
  }

  // Getter a token értékhez
  const getToken = (): string | null => {
    return token.value
  }

  return {
    token: readonly(token),
    isLoaded: readonly(isLoaded),
    loadToken,
    setToken,
    clearToken,
    getToken
  }
}
