import { defineStore } from 'pinia'
import { ref } from 'vue'
import { API } from '@/Api'
import { toast } from 'vue-sonner'

export interface JobBlob {
  status: 'pending' | 'running' | 'success' | 'failure' | string
  jobId?: string
}
interface TrackedJob {
  blob: JobBlob
  name: string
}
interface BulkResult {
  indexing: JobBlob
  documents?: any[]
}

export const useIndexingStore = defineStore('indexing', () => {
  const jobs = ref<Record<string, TrackedJob>>({})

  let timer: number | null = null

  function track(agentId: string, blob?: JobBlob, agentName?: string) {
    if (!blob || !agentName) return
    jobs.value[agentId] = { blob, name: agentName }
    ensureTimer()
  }

  function untrack(agentId: string) {
    delete jobs.value[agentId]
    if (!Object.keys(jobs.value).length) stopTimer()
  }

  function ensureTimer() {
    if (timer !== null) return
    timer = window.setInterval(tick, 4000)
  }
  function stopTimer() {
    if (timer !== null) {
      clearInterval(timer)
      timer = null
    }
  }

  async function tick() {
    const ids = Object.keys(jobs.value)
    if (!ids.length) return stopTimer()

    try {
      const { data } = await API.getIndexStatusBulk(ids)
      const results: Record<string, BulkResult> = data.results || {}

      for (const [aid, res] of Object.entries(results)) {
        const job = jobs.value[aid]
        if (!job) continue

        job.blob = res.indexing

        if (res.indexing.status === 'success' || res.indexing.status === 'failure') {
          window.dispatchEvent(
            new CustomEvent('docs-updated', {
              detail: { agentId: aid, docs: res.documents || [], indexing: res.indexing },
            })
          )
          if (res.indexing.status === 'failure')
            toast.error(`Document(s) processing failed for "${job.name}"`, {
              duration: Infinity, // Makes the toast stay indefinitely
              dismissible: true, // Allows user to dismiss the toast
              important: true, // Gives higher priority to this toast
              action: {
                label: 'Dismiss',
              },
            })
          else if (res.indexing.status === 'success')
            toast.success(`Document(s) processing complete for “${job.name}”`)
          delete jobs.value[aid]
        }
      }
    } catch (e) {
      console.error('Bulk index-status polling failed', e)
    }

    if (!Object.keys(jobs.value).length) stopTimer()
  }

  return { track, untrack }
})
