import { defineStore } from 'pinia'
import { apiFetch } from '../services/api'

interface DashboardStatusDto {
  gatewayOk: boolean
  irisStatus: string
  activeAgents: number
  pendingTasks: number
}

interface FeedEntryDto {
  agent: string
  action: string
  timestamp: string
  time: string
  agentId?: string | null
  type?: string | null
}

interface QueueItemDto {
  id: string
  name: string
  status: string
  priority: string
  source: string
  waitTime: string
}

export const useDashboardStore = defineStore('dashboard', {
  state: () => ({
    status: null as DashboardStatusDto | null,
    operations: [] as FeedEntryDto[],
    queue: [] as QueueItemDto[],
    loading: false,
    error: null as string | null,
    refreshInterval: null as ReturnType<typeof setInterval> | null,
  }),

  getters: {
    isGatewayConnected: state => state.status?.gatewayOk ?? false,
    irisStatusLabel: state => state.status?.irisStatus ?? 'Offline',
  },

  actions: {
    async fetchStatus() {
      try {
        const res = await apiFetch('/api/dashboard/status')
        if (!res.ok) throw new Error(`HTTP ${res.status}`)
        this.status = await res.json()
      } catch (err) {
        console.warn('[DashboardStore] fetchStatus failed', err)
        this.status = null
      }
    },

    async fetchOperations() {
      try {
        const res = await apiFetch('/api/dashboard/operations?limit=20')
        if (!res.ok) throw new Error(`HTTP ${res.status}`)
        this.operations = await res.json()
      } catch (err) {
        console.warn('[DashboardStore] fetchOperations failed', err)
        this.operations = []
      }
    },

    async fetchQueue() {
      try {
        const res = await apiFetch('/api/dashboard/queue')
        if (!res.ok) throw new Error(`HTTP ${res.status}`)
        this.queue = await res.json()
      } catch (err) {
        console.warn('[DashboardStore] fetchQueue failed', err)
        this.queue = []
      }
    },

    async refresh() {
      this.loading = true
      try {
        await Promise.all([
          this.fetchStatus(),
          this.fetchOperations(),
          this.fetchQueue(),
        ])
        this.error = null
      } catch (err) {
        console.warn('[DashboardStore] refresh failed', err)
        this.error = 'Dashboard metadata could not be loaded'
      } finally {
        this.loading = false
      }
    },

    startPolling() {
      if (this.refreshInterval) return
      this.refresh()
      this.refreshInterval = setInterval(() => {
        this.refresh()
      }, 30000)
    },

    stopPolling() {
      if (this.refreshInterval) {
        clearInterval(this.refreshInterval)
        this.refreshInterval = null
      }
    },
  },
})
