import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getMatterCard, getMatterRequirements, searchMatters } from '@/api/matter'
import type { MatterCardResponse, MatterListItem } from '@/types/matter'

export const useMatterStore = defineStore('matter', () => {
  const query = ref('')
  const results = ref<MatterListItem[]>([])
  const currentMatter = ref<MatterCardResponse | null>(null)
  const loading = ref(false)
  const detailLoading = ref(false)

  async function search(searchTerm?: string) {
    const normalized = (searchTerm ?? query.value).trim()
    query.value = normalized

    if (!normalized) {
      results.value = []
      return
    }

    loading.value = true
    try {
      results.value = await searchMatters(normalized)
    } catch (error) {
      console.error('Matter search failed:', error)
      results.value = []
    } finally {
      loading.value = false
    }
  }

  async function loadCard(matterId: string) {
    detailLoading.value = true
    currentMatter.value = null

    try {
      const [cardResult, requirementsResult] = await Promise.allSettled([
        getMatterCard(matterId),
        getMatterRequirements(matterId),
      ])

      if (cardResult.status !== 'fulfilled') {
        throw cardResult.reason
      }

      const card = cardResult.value
      if (requirementsResult.status === 'fulfilled') {
        card.conditions = requirementsResult.value.conditions
        card.materials = requirementsResult.value.materials
        card.time_limits = requirementsResult.value.time_limits
      }

      currentMatter.value = card
    } catch (error) {
      console.error('Matter detail failed:', error)
      currentMatter.value = null
      throw error
    } finally {
      detailLoading.value = false
    }
  }

  function clearCurrentMatter() {
    currentMatter.value = null
  }

  return {
    query,
    results,
    currentMatter,
    loading,
    detailLoading,
    search,
    loadCard,
    clearCurrentMatter,
  }
})