import type { SyncedPreferences } from '~/composables/use-preferences'
import chadApi from '#shared/chad-api'

export default defineNuxtRouteMiddleware(async () => {
  const { me } = useAuth()

  if (!me.value)
    return

  const { synced, toggleInputHotkey, toggleOutputHotkey } = usePreferences()

  if (synced.value)
    return

  try {
    const preferences = await chadApi<SyncedPreferences>('/preferences', { method: 'GET' })

    if (!preferences)
      return

    toggleInputHotkey.value = preferences.toggleInputHotkey ?? toggleInputHotkey.value
    toggleOutputHotkey.value = preferences.toggleOutputHotkey ?? toggleOutputHotkey.value
    synced.value = true
  }
  catch {}
})
