import chadApi from '#shared/chad-api'
import { createGlobalState } from '@vueuse/core'

interface Me {
  id: string
  username: string
  displayName: string
}

export const useAuth = createGlobalState(() => {
  const me = shallowRef<Me>()

  function setMe(value: Me | undefined): void {
    me.value = value
  }

  async function login(username: string, password: string): Promise<void> {
    try {
      const result = await chadApi<Me>('/login', {
        method: 'POST',
        body: {
          username,
          password,
        },
      })

      setMe(result)

      await navigateTo('/')
    }
    catch {}
  }

  async function register(username: string, password: string): Promise<void> {
    try {
      const result = await chadApi<Me>('/register', {
        method: 'POST',
        body: {
          username,
          password,
        },
      })

      setMe(result)

      await navigateTo('/')
    }
    catch {}
  }

  async function logout(): Promise<void> {
    try {
      await chadApi('/logout', { method: 'POST' })

      setMe(undefined)

      await navigateTo({ name: 'Login' })
    }
    catch {}
  }

  return {
    me: readonly(me),
    setMe,
    login,
    register,
    logout,
  }
})
