import { defineStore } from 'pinia' import { ref } from 'vue' import { apiRequest } from '../lib/api' import type { TodoItem } from '../types' type ItemPatch = Partial> export const useItemsStore = defineStore('items', () => { // Held in list order (by position); mutated in place by drag-and-drop. const items = ref([]) const listId = ref(null) const loading = ref(false) const loaded = ref(false) const completedCount = () => items.value.filter((i) => i.complete).length async function load(id: number): Promise { listId.value = id loaded.value = false loading.value = true try { const { items: fetched } = await apiRequest<{ items: TodoItem[] }>(`/lists/${id}/items`, { auth: true, }) items.value = fetched loaded.value = true } finally { loading.value = false } } async function add(text: string): Promise { const { item } = await apiRequest<{ item: TodoItem }>(`/lists/${listId.value}/items`, { method: 'POST', auth: true, body: { text }, }) // The API appends the item, so the end of the array is its correct place. items.value.push(item) } async function patch(item: TodoItem, fields: ItemPatch): Promise { const { item: updated } = await apiRequest<{ item: TodoItem }>( `/lists/${listId.value}/items/${item.id}`, { method: 'PATCH', auth: true, body: fields }, ) const i = items.value.findIndex((x) => x.id === updated.id) if (i !== -1) items.value[i] = updated } const setComplete = (item: TodoItem, complete: boolean) => patch(item, { complete }) const setText = (item: TodoItem, text: string) => patch(item, { text }) async function remove(item: TodoItem): Promise { await apiRequest(`/lists/${listId.value}/items/${item.id}`, { method: 'DELETE', auth: true }) items.value = items.value.filter((i) => i.id !== item.id) } /** Persist the current array order (call after a drag ends). */ async function persistOrder(): Promise { const { items: fresh } = await apiRequest<{ items: TodoItem[] }>( `/lists/${listId.value}/items/order`, { method: 'PUT', auth: true, body: { item_ids: items.value.map((i) => i.id) } }, ) items.value = fresh } function reset(): void { items.value = [] listId.value = null loaded.value = false } return { items, listId, loading, loaded, completedCount, load, add, setComplete, setText, remove, persistOrder, reset, } })