import { defineStore } from 'pinia'
import { ref } from 'vue'
import { invoke } from '@tauri-apps/api/core'
import { handleInvokeError } from '../utils/errorHandler'

export interface Client {
  id?: number
  name: string
  email?: string
  address?: string
  company?: string
  phone?: string
  tax_id?: string
  payment_terms?: string
  notes?: string
  currency?: string
}

export const useClientsStore = defineStore('clients', () => {
  const clients = ref<Client[]>([])
  const loading = ref(false)

  async function fetchClients() {
    loading.value = true
    try {
      clients.value = await invoke<Client[]>('get_clients')
    } catch (error) {
      handleInvokeError(error, 'Failed to fetch clients', () => fetchClients())
    } finally {
      loading.value = false
    }
  }

  async function createClient(client: Client): Promise<number | null> {
    try {
      const id = await invoke<number>('create_client', { client })
      clients.value.push({ ...client, id: Number(id) })
      return Number(id)
    } catch (error) {
      handleInvokeError(error, 'Failed to create client')
      return null
    }
  }

  async function updateClient(client: Client): Promise<boolean> {
    try {
      await invoke('update_client', { client })
      const index = clients.value.findIndex(c => c.id === client.id)
      if (index !== -1) {
        clients.value[index] = client
      }
      return true
    } catch (error) {
      handleInvokeError(error, 'Failed to update client')
      return false
    }
  }

  async function deleteClient(id: number): Promise<boolean> {
    try {
      await invoke('delete_client', { id })
      clients.value = clients.value.filter(c => c.id !== id)
      return true
    } catch (error) {
      handleInvokeError(error, 'Failed to delete client')
      return false
    }
  }

  return {
    clients,
    loading,
    fetchClients,
    createClient,
    updateClient,
    deleteClient
  }
})
