import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { projectsApi, type Project, type Visibility } from '@/api/projects'

export const useProjectsStore = defineStore('projects', () => {
  const items = ref<Project[]>([])
  const current = ref<Project | null>(null)
  const includeArchived = ref(false)
  const loading = ref(false)

  async function refresh() {
    loading.value = true
    try {
      const out = await projectsApi.list(includeArchived.value)
      items.value = out.items
    } finally {
      loading.value = false
    }
  }

  async function load(slug: string) {
    current.value = await projectsApi.get(slug)
    return current.value
  }

  async function create(body: { slug: string; name: string; description?: string; visibility?: Visibility }) {
    const p = await projectsApi.create(body)
    items.value = [p, ...items.value]
    return p
  }

  async function archive(slug: string) {
    await projectsApi.archive(slug)
    await refresh()
    if (current.value?.slug === slug) current.value = await projectsApi.get(slug)
  }

  async function unarchive(slug: string) {
    await projectsApi.unarchive(slug)
    await refresh()
    if (current.value?.slug === slug) current.value = await projectsApi.get(slug)
  }

  const archivedItems = computed(() => items.value.filter((p) => p.archived_at))
  const activeItems = computed(() => items.value.filter((p) => !p.archived_at))

  return { items, current, loading, includeArchived, archivedItems, activeItems, refresh, load, create, archive, unarchive }
})
