import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useApi } from '@/composables/useApi'

// ---------------------------------------------------------------------------
// Types — mirrors the FleetResponseDto from the backend
// ---------------------------------------------------------------------------

export interface FleetDisk {
  mount: string
  total_mb: number
  free_mb: number
}

export interface FleetInstance {
  id: string
  agent_instance_id: string
  game: string
  label: string | null
  state: string
  uptime_seconds: number
  last_seen_at: string | null
}

export interface FleetHost {
  id: string
  hostname: string
  status: string
  agent_version: string | null
  os: string | null
  arch: string | null
  cpu_percent: number | null
  cpu_cores: number | null
  mem_total_mb: number | null
  mem_used_mb: number | null
  uptime_seconds: number | null
  disks: FleetDisk[] | null
  last_heartbeat_at: string | null
  instances: FleetInstance[]
}

export interface FleetSummary {
  host_count: number
  instance_count: number
  online_host_count: number
}

export interface FleetData {
  hosts: FleetHost[]
  summary: FleetSummary
}

// ---------------------------------------------------------------------------
// Store
// ---------------------------------------------------------------------------

export const useFleetStore = defineStore('fleet', () => {
  const hosts = ref<FleetHost[]>([])
  const summary = ref<FleetSummary>({ host_count: 0, instance_count: 0, online_host_count: 0 })
  const loading = ref(false)
  const error = ref<string | null>(null)

  const api = useApi()

  async function fetchFleet() {
    loading.value = true
    error.value = null
    try {
      const data = await api.get<FleetData>('/fleet')
      hosts.value = data.hosts
      summary.value = data.summary
    } catch (e) {
      console.error('Failed to fetch fleet:', e)
      error.value = e instanceof Error ? e.message : 'Failed to load fleet data'
    } finally {
      loading.value = false
    }
  }

  /**
   * Remove a host and its instances. Throws on failure (e.g. 409 when the host
   * is still online) so the caller can surface the message; refetches on
   * success.
   */
  async function removeHost(hostId: string): Promise<void> {
    await api.del(`/fleet/hosts/${hostId}`)
    await fetchFleet()
  }

  return {
    hosts,
    summary,
    loading,
    error,
    fetchFleet,
    removeHost,
  }
})
