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

export interface EntryTemplate {
  id?: number
  name: string
  project_id: number
  task_id?: number
  description?: string
  duration: number
  billable: number
  created_at?: string
}

export const useEntryTemplatesStore = defineStore('entryTemplates', () => {
  const templates = ref<EntryTemplate[]>([])
  const loading = ref(false)

  async function fetchTemplates() {
    loading.value = true
    try {
      templates.value = await invoke<EntryTemplate[]>('get_entry_templates')
    } catch (error) {
      handleInvokeError(error, 'Failed to fetch entry templates', () => fetchTemplates())
    } finally {
      loading.value = false
    }
  }

  async function createTemplate(template: Omit<EntryTemplate, 'id' | 'created_at'>): Promise<number | null> {
    try {
      const id = await invoke<number>('create_entry_template', { template })
      templates.value.push({ ...template, id: Number(id) })
      return Number(id)
    } catch (error) {
      handleInvokeError(error, 'Failed to create template')
      return null
    }
  }

  async function updateTemplate(template: EntryTemplate): Promise<boolean> {
    try {
      await invoke('update_entry_template', { template })
      const index = templates.value.findIndex(t => t.id === template.id)
      if (index !== -1) {
        templates.value[index] = template
      }
      return true
    } catch (error) {
      handleInvokeError(error, 'Failed to update template')
      return false
    }
  }

  async function deleteTemplate(id: number) {
    try {
      await invoke('delete_entry_template', { id })
      templates.value = templates.value.filter(t => t.id !== id)
    } catch (error) {
      handleInvokeError(error, 'Failed to delete template')
    }
  }

  return { templates, loading, fetchTemplates, createTemplate, updateTemplate, deleteTemplate }
})
