import { defineStore } from 'pinia'
import { ref } from 'vue'
import {
  projectsApi,
  type Artifact,
  type ArtifactPhase,
  type Phase,
  type Requirement,
  type Status,
} from '@/api/projects'

export const useRequirementsStore = defineStore('requirements', () => {
  const items = ref<Requirement[]>([])
  const slug = ref<string>('')
  const loading = ref(false)
  const filterPhase = ref<Phase | ''>('')
  const filterStatus = ref<Status | ''>('')

  async function refresh(forSlug: string) {
    slug.value = forSlug
    loading.value = true
    try {
      const out = await projectsApi.listRequirements(forSlug, {
        phase: filterPhase.value || undefined,
        status: filterStatus.value || undefined,
      })
      items.value = out.items
    } finally {
      loading.value = false
    }
  }

  async function create(forSlug: string, body: { title: string; description?: string }) {
    const r = await projectsApi.createRequirement(forSlug, body)
    items.value = [r, ...items.value]
    return r
  }

  async function changePhase(forSlug: string, number: number, phase: Phase) {
    const out = await projectsApi.changeRequirementPhase(forSlug, number, phase)
    items.value = items.value.map((x) => (x.number === number ? out : x))
    return out
  }

  async function close(forSlug: string, number: number) {
    await projectsApi.closeRequirement(forSlug, number)
    await refresh(forSlug)
  }

  async function reopen(forSlug: string, number: number) {
    await projectsApi.reopenRequirement(forSlug, number)
    await refresh(forSlug)
  }

  async function listArtifacts(
    forSlug: string,
    number: number,
    phase?: ArtifactPhase,
  ): Promise<Artifact[]> {
    return await projectsApi.listArtifacts(forSlug, number, phase)
  }

  async function createArtifact(
    forSlug: string,
    number: number,
    body: { phase: ArtifactPhase; content: string; note?: string; source_message_id?: number },
  ): Promise<Artifact> {
    return await projectsApi.createArtifact(forSlug, number, body)
  }

  async function getArtifact(
    forSlug: string,
    number: number,
    phase: ArtifactPhase,
    version: number,
  ): Promise<Artifact> {
    return await projectsApi.getArtifact(forSlug, number, phase, version)
  }

  return {
    items,
    slug,
    loading,
    filterPhase,
    filterStatus,
    refresh,
    create,
    changePhase,
    close,
    reopen,
    listArtifacts,
    createArtifact,
    getArtifact,
  }
})
