import { defineStore } from 'pinia'
import { ref } from 'vue'
import * as api from '../api/client.js'

export const useCloudConnectionsStore = defineStore('cloudConnections', () => {
  const connections = ref([])
  const loading = ref(false)
  const error = ref(null)

  async function fetchConnections() {
    loading.value = true
    error.value = null
    try {
      const data = await api.listCloudConnections()
      connections.value = data.items ?? []
    } catch (e) {
      error.value = e.message || 'Failed to load cloud connections'
    } finally {
      loading.value = false
    }
  }

  async function disconnect(id) {
    try {
      await api.disconnectCloud(id)
      connections.value = connections.value.filter(c => c.id !== id)
    } catch (e) {
      throw e
    }
  }

  async function disconnectAll() {
    const ids = connections.value.map(c => c.id)
    for (const id of ids) await disconnect(id)
    connections.value = []
  }

  return { connections, loading, error, fetchConnections, disconnect, disconnectAll }
})
