// filepath: src/stores/queue.ts
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { listen } from '@tauri-apps/api/event'

export interface DownloadTask {
  id: string
  title: string
  thumbnail: string
  progress: number
  speed: string
  status: 'pending' | 'downloading' | 'finished' | 'error'
}

interface ProgressEvent {
  id: string
  progress: number
  speed: string
  status: string
}

export const useQueueStore = defineStore('queue', () => {
  const tasks = ref<DownloadTask[]>([])
  const isListening = ref(false)

  function addTask(task: DownloadTask) {
    tasks.value.push(task)
  }

  async function initListener() {
    if (isListening.value) return
    isListening.value = true
    
    await listen<ProgressEvent>('download-progress', (event) => {
      const { id, progress, speed, status } = event.payload
      const task = tasks.value.find(t => t.id === id)
      if (task) {
        task.progress = progress
        task.speed = speed
        // Map status string to type if needed, or just assign
        task.status = status as any
      }
    })
  }

  return { tasks, addTask, initListener }
})
