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

export const useTasksStore = defineStore('tasks', {
  state: () => ({
    tasks: [],
    currentTasks: [],
    availableStatuses: [],
    loading: false,
    error: null,
  }),

  actions: {
    async fetchAll() {
      this.loading = true
      this.error = null
      try {
        this.tasks = await taskApi.list()
      } catch (e) {
        this.error = e.message
      } finally {
        this.loading = false
      }
    },

    async fetchCurrent() {
      this.loading = true
      this.error = null
      try {
        this.currentTasks = await taskApi.list('current')
      } catch (e) {
        this.error = e.message
      } finally {
        this.loading = false
      }
    },

    async get(id) {
      return taskApi.get(id)
    },

    async fetchStatuses() {
      if (this.availableStatuses.length > 0) return
      this.availableStatuses = await taskApi.statuses()
    },

    async update(id, data) {
      const updated = await taskApi.update(id, data)
      this.replaceLocal(updated)
      return updated
    },

    async remove(id) {
      await taskApi.remove(id)
      this.tasks = this.tasks.filter((t) => t.id !== id)
      this.currentTasks = this.currentTasks.filter((t) => t.id !== id)
    },

    async toggle(id) {
      const updated = await taskApi.toggle(id)
      this.replaceLocal(updated)
      return updated
    },

    replaceLocal(task) {
      const replace = (list) => list.map((t) => (t.id === task.id ? task : t))
      this.tasks = replace(this.tasks)
      this.currentTasks = replace(this.currentTasks)
    },
  },
})
