import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Contract, ContractStatus } from '../types'
import {
  getContractList,
  deleteContract as apiDeleteContract
} from '../api/contract'

export const useContractStore = defineStore('contract', () => {
  const contracts = ref<Contract[]>([])
  const currentContract = ref<Contract | null>(null)
  const keyword = ref('')
  const status = ref<ContractStatus | ''>('')
  const loading = ref(false)
  const loadingMore = ref(false)
  const pageNum = ref(1)
  const pageSize = ref(10)
  const total = ref(0)

  const hasMore = computed(() => contracts.value.length < total.value)
  const totalCount = computed(() => total.value)

  async function fetchContracts(reset = false) {
    if (reset) {
      pageNum.value = 1
      contracts.value = []
    }
    loading.value = true
    try {
      const res = await getContractList(pageNum.value, pageSize.value, {
        keyword: keyword.value || undefined,
        status: status.value || undefined
      })
      const rows = res.rows || []
      contracts.value = reset ? rows : [...contracts.value, ...rows]
      total.value = res.total || 0
    } finally {
      loading.value = false
    }
  }

  async function loadMore() {
    if (loadingMore.value || !hasMore.value) return
    loadingMore.value = true
    pageNum.value++
    try {
      const res = await getContractList(pageNum.value, pageSize.value, {
        keyword: keyword.value || undefined,
        status: status.value || undefined
      })
      contracts.value = [...contracts.value, ...(res.rows || [])]
    } catch (error) {
      pageNum.value--
    } finally {
      loadingMore.value = false
    }
  }

  function setKeyword(value: string) {
    keyword.value = value
  }

  function setStatus(value: ContractStatus | '') {
    status.value = value
  }

  function setCurrentContract(id: number | string) {
    currentContract.value = contracts.value.find(c => String(c.id) === String(id)) || null
  }

  async function removeContract(id: number | string) {
    await apiDeleteContract(id)
    contracts.value = contracts.value.filter(c => String(c.id) !== String(id))
    total.value--
  }

  return {
    contracts,
    currentContract,
    keyword,
    status,
    loading,
    loadingMore,
    pageNum,
    pageSize,
    total,
    hasMore,
    totalCount,
    fetchContracts,
    loadMore,
    setKeyword,
    setStatus,
    setCurrentContract,
    removeContract
  }
})
