import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useApi } from '../composables/useApi.js'

// Provenance is its own system — this store is deliberately independent
// of the modal/tags stores (see project_provenance_separation).
export const useProvenanceStore = defineStore('provenance', () => {
  const api = useApi()

  const imageCache = ref({})  // id -> { loading, error, entries|null }
  const postCache = ref({})   // id -> { loading, error, data|null }

  async function loadForImage(id) {
    const cur = imageCache.value[id]
    if (cur && (cur.loading || cur.entries !== null)) return
    imageCache.value[id] = { loading: true, error: null, entries: null }
    try {
      const body = await api.get(`/api/provenance/image/${id}`)
      imageCache.value[id] = {
        loading: false, error: null,
        entries: body.provenance,
        attachments: body.attachments || [],
      }
    } catch (e) {
      imageCache.value[id] =
        { loading: false, error: e.message, entries: null }
    }
  }

  async function loadForPost(id) {
    const cur = postCache.value[id]
    if (cur && (cur.loading || cur.data !== null)) return
    postCache.value[id] = { loading: true, error: null, data: null }
    try {
      const body = await api.get(`/api/provenance/post/${id}`)
      postCache.value[id] = { loading: false, error: null, data: body }
    } catch (e) {
      postCache.value[id] = { loading: false, error: e.message, data: null }
    }
  }

  function imageProv(id) { return imageCache.value[id] || null }
  function postInfo(id) { return postCache.value[id] || null }

  return { imageCache, postCache, loadForImage, loadForPost,
           imageProv, postInfo }
})
