import { ref, reactive, onMounted, onActivated, onUnmounted } from 'vue'
import { usePushForm } from './usePushForm'
import { usePushServers } from './usePushServers'
import { usePushProgress } from './usePushProgress'
import { usePushPreview } from './usePushPreview'
import { usePushLogs } from './usePushLogs'
import { usePushStaging } from './usePushStaging'

/** Orchestrates push page composables and lifecycle */
export function usePushPage() {
  const form = usePushForm()
  const staging = usePushStaging(form.uploadedSource)
  const pushStatus = ref<Record<number, string>>({})
  const servers = usePushServers(pushStatus)
  const logs = usePushLogs(form, servers)
  const progress = usePushProgress(form, servers, () => logs.loadLogs())
  const preview = usePushPreview(form, servers)

  function onConfirmAndPush() {
    preview.confirmAndPush(() => progress.doPush())
  }

  let pushReady = false

  function refreshPush(silent = false) {
    if (!silent) {
      servers.loadServers()
      logs.loadLogs()
    } else {
      void servers.loadServers(true)
      void logs.loadLogs(true)
    }
  }

  onMounted(() => {
    refreshPush(false)
    void servers.loadSearchHistory()
    servers.startAutoRefresh(() => progress.pushing.value)
    pushReady = true
  })

  onActivated(() => {
    if (pushReady) refreshPush(true)
  })

  onUnmounted(() => {
    progress.dispose()
    servers.stopAutoRefresh()
  })

  return {
    form: reactive(form),
    staging: reactive(staging),
    servers: reactive(servers),
    progress: reactive(progress),
    preview: reactive(preview),
    logs: reactive(logs),
    onConfirmAndPush,
  }
}
