import { onBeforeUnmount, ref } from 'vue'
import type { KbxImportProgressEvent } from '@kbx/contracts'

export interface KbxImportProgressConnection {
  start(): Promise<void>
  stop(): Promise<void>
  subscribe(sessionId: string): Promise<void>
  unsubscribe(sessionId: string): Promise<void>
  onProgress(callback: (event: KbxImportProgressEvent) => void): void
}

/**
 * SignalR is intentionally hidden behind this adapter.
 * The app shell can provide a @microsoft/signalr implementation without
 * coupling KbxExcelImport or a vertical slice to HubConnection directly.
 */
export function useKbxImportProgress(connection: KbxImportProgressConnection | null) {
  const connected = ref(false)
  const lastEvent = ref<KbxImportProgressEvent | null>(null)
  let activeSessionId: string | null = null

  if (connection) {
    connection.onProgress(event => {
      if (!activeSessionId || event.sessionId === activeSessionId)
        lastEvent.value = event
    })
  }

  async function connect() {
    if (!connection || connected.value) return
    await connection.start()
    connected.value = true
  }

  async function watch(sessionId: string) {
    if (!connection) return
    await connect()
    if (activeSessionId && activeSessionId !== sessionId)
      await connection.unsubscribe(activeSessionId)
    activeSessionId = sessionId
    await connection.subscribe(sessionId)
  }

  async function dispose() {
    if (!connection) return
    if (activeSessionId) await connection.unsubscribe(activeSessionId)
    if (connected.value) await connection.stop()
    connected.value = false
    activeSessionId = null
  }

  onBeforeUnmount(() => { void dispose() })

  return { connected, lastEvent, watch, dispose }
}
