/**
 * Socket project bootstrap
 *
 * Flow:
 * 1. Server emits joinConfirmation → client dispatches projectInit (resets project-scoped store slices)
 * 2. projectInit completes → store emits store_actionResolved_{resolveId}
 * 3. onProjectInitResolved runs setupSpace, syncs route compositions, emits ui/setupProject
 */
import type { Composition } from "@shared/types/core/Composition.types"
import type { InteractionLink } from "@shared/types/core/InteractionLink.types"
import { setupSpace } from "@racletteCore/lib/projectDataHelper"
import type { ProjectConfiguration } from "../store/types"
import type EventEmitter from "@racletteCore/lib/eventEmitter"
import type { RacletteStore } from "@racletteCore"

export type ProjectBootstrapPayload = {
  compositions?: Composition[]
  interactionLinks?: InteractionLink[]
  projectConfig?: ProjectConfiguration
  project?: { _id: string; account: string }
  roomId: string
  /** Runs after setupSpace (e.g. work-session fullscreen UI). */
  afterSetup?: () => void | Promise<void>
}

type BootstrapDeps = {
  store: RacletteStore
  eventbus: EventEmitter
}

/**
 * Registers the post-projectInit handler, then resets project-scoped store state.
 */
export const startProjectBootstrap = (
  { store, eventbus }: BootstrapDeps,
  resolveId: string,
  payload: ProjectBootstrapPayload,
) => {
  const {
    compositions,
    interactionLinks,
    projectConfig,
    project,
    roomId,
    afterSetup,
  } = payload

  eventbus.once(`store_actionResolved_${resolveId}`, async () => {
    if (project) {
      store.dispatch({
        type: "project/set",
        payload: project,
      })
    }

    store.dispatch({
      type: "ui/update",
      payload: { loading: true },
    })

    // Same setupSpace as logged-in users (landing page detection, etc.)
    await setupSpace(
      compositions || [],
      interactionLinks || [],
      projectConfig || {},
    )
    // Re-apply route composition slots after projectInit cleared ui.page
    eventbus.emit("ui/syncRouteCompositions")
    await afterSetup?.()

    store.dispatch({
      type: "ui/update",
      payload: { loading: false },
    })

    eventbus.emit("ui/setupProject", roomId)
  })

  store.dispatch({
    type: "projectInit",
    resolveId,
  })
}
