import type { App as VueApp } from "vue"
import createRacletteApp, { corePluginApi } from "@racletteCore/main"
import { extractSessionIdFromUrl } from "@racletteCore/lib/workSessionUrl"
import { createVueApp, createLoginVueApp } from "./main"
import { initApp } from "./setup/application"
export * from "./exports"

const VUE_MOUNTING_ELEMENT = "#app"
let currentApp: VueApp | undefined

const startApp = async () => {
  try {
    // Check if URL indicates a work session
    const sessionId = extractSessionIdFromUrl()

    const res = await createRacletteApp({
      requireAuth: !sessionId,
      sessionId: sessionId || undefined,
    })

    if (currentApp) {
      currentApp.unmount()
      currentApp = undefined
    }

    if (!res.authenticated && !sessionId) {
      const noUsers = res.code === "RCLT_DB_NO_USERS"
      if (res.login) {
        currentApp = await createLoginVueApp(
          VUE_MOUNTING_ELEMENT,
          res.login,
          noUsers,
        )
      }
    } else {
      currentApp = await createVueApp(VUE_MOUNTING_ELEMENT)
      await initApp(corePluginApi)
    }
  } catch (err) {
    console.error("Failed to start app:", err)
  }
}

startApp()
