/**
 * 连接状态 Pinia Store
 */

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { connectionManager, type ConnectionProfile, type ConnectionState } from '@/api/connection-manager'

export const useConnectionStore = defineStore('connection', () => {
  const state = ref<ConnectionState>(connectionManager.state)
  const activeProfile = ref<ConnectionProfile | null>(connectionManager.activeProfile)

  connectionManager.onStateChange((s) => { state.value = s })

  const isConnected = computed(() => state.value === 'connected')
  const isRemote = computed(() => connectionManager.isRemote())
  const fileServerBaseURL = computed(() => connectionManager.getFileServerBaseURL())

  async function connect(id: string) {
    try {
      await connectionManager.connect(id)
    } catch {
      // 连接失败，回退到本地
      connectionManager.disconnect()
    }
    activeProfile.value = connectionManager.activeProfile
  }

  function disconnect() {
    connectionManager.disconnect()
    activeProfile.value = connectionManager.activeProfile
  }

  function refresh() {
    activeProfile.value = connectionManager.activeProfile
    state.value = connectionManager.state
  }

  return {
    state,
    activeProfile,
    isConnected,
    isRemote,
    fileServerBaseURL,
    connect,
    disconnect,
    refresh,
  }
})
