import type { UserSession, UserSessionComposable } from '~/types/auth'

const useSessionState = () => useState<UserSession>('nuxt-session', () => ({}))
const useAuthReadyState = () => useState('nuxt-auth-ready', () => false)

/**
 * Composable to get back the user session and utils around it.
 */
export function useUserSession(): UserSessionComposable {
  const sessionState = useSessionState()
  const authReadyState = useAuthReadyState()
  return {
    ready: computed(() => authReadyState.value),
    loggedIn: computed(() => Boolean(sessionState.value.user)),
    user: computed(() => sessionState.value.user ?? null),
    session: sessionState,
    fetch,
    clear,
  }
}

async function fetch(): Promise<boolean> {
  const authReadyState = useAuthReadyState()
  const sessionState = useSessionState()
  const loggedIn = Boolean(sessionState.value.user)
  sessionState.value = await useRequestFetch()('/api/auth/session').catch(() => ({}))
  if (!authReadyState.value)
  {
    authReadyState.value = true
  }
  return loggedIn !== Boolean(sessionState.value.user);
}

async function clear() {
  await useRequestFetch()('/api/auth/session', { method: 'DELETE' })
  useSessionState().value = {}
  useRouter().go(0)
}