import { defineStore } from 'pinia' import { ref } from 'vue' import { listPublications, getPublication, createPublication, updatePublication, deletePublication, type Publication, type PublicationWriteDTO, } from '../api/publications' export const usePublicationStore = defineStore('publication', () => { const publications = ref([]) const current = ref(null) const loading = ref(false) const error = ref(null) async function fetchPublications() { loading.value = true error.value = null try { publications.value = await listPublications() } catch (e) { error.value = e instanceof Error ? e.message : 'unknown error' } finally { loading.value = false } } async function fetchPublication(id: number) { loading.value = true error.value = null try { current.value = await getPublication(id) } catch (e) { error.value = e instanceof Error ? e.message : 'unknown error' current.value = null } finally { loading.value = false } } async function create(dto: PublicationWriteDTO): Promise { const pub = await createPublication(dto) publications.value = [pub, ...publications.value] return pub } async function update(id: number, dto: PublicationWriteDTO): Promise { const pub = await updatePublication(id, dto) const idx = publications.value.findIndex((p) => p.id === id) if (idx !== -1) publications.value[idx] = pub if (current.value?.id === id) current.value = pub return pub } async function remove(id: number) { await deletePublication(id) publications.value = publications.value.filter((p) => p.id !== id) if (current.value?.id === id) current.value = null } return { publications, current, loading, error, fetchPublications, fetchPublication, create, update, remove } })