import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Customer } from '../types'
import {
  getCustomerList,
  deleteCustomer as apiDeleteCustomer
} from '../api/customer'

export const useCustomerStore = defineStore('customer', () => {
  const customers = ref<Customer[]>([])
  const currentCustomer = ref<Customer | null>(null)
  const keyword = ref('')
  const loading = ref(false)
  const loadingMore = ref(false)
  const pageNum = ref(1)
  const pageSize = ref(10)
  const total = ref(0)

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

  async function fetchCustomers(reset = false) {
    if (reset) {
      pageNum.value = 1
      customers.value = []
    }
    loading.value = true
    try {
      const res = await getCustomerList(pageNum.value, pageSize.value, keyword.value || undefined)
      const rows = res.rows || []
      customers.value = reset ? rows : [...customers.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 getCustomerList(pageNum.value, pageSize.value, keyword.value || undefined)
      customers.value = [...customers.value, ...(res.rows || [])]
    } catch (error) {
      pageNum.value--
    } finally {
      loadingMore.value = false
    }
  }

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

  function setCurrentCustomer(id: number | string) {
    currentCustomer.value = customers.value.find(c => String(c.id) === String(id)) || null
  }

  async function removeCustomer(id: number | string) {
    await apiDeleteCustomer(id)
    customers.value = customers.value.filter(c => String(c.id) !== String(id))
    total.value--
  }

  return {
    customers,
    currentCustomer,
    keyword,
    loading,
    loadingMore,
    pageNum,
    pageSize,
    total,
    hasMore,
    totalCount,
    fetchCustomers,
    loadMore,
    setKeyword,
    setCurrentCustomer,
    removeCustomer
  }
})
