import { storeToRefs } from 'pinia'
import { useExpensesStore } from '@/stores/expensesStore'
import type { CreateExpenseData, UpdateExpenseData } from '@/services/expenseService'
import type { SettlementActivityCreate } from '@/types/expense'

export function useExpenses() {
  // Get store instance
  const expensesStore = useExpensesStore()

  // Expose reactive refs from store
  const {
    expenses,
    recurringExpenses,
    isLoading: loading,
    error,
  } = storeToRefs(expensesStore)

  // Delegate actions
  const {
    fetchExpenses,
    createExpense,
    updateExpense,
    deleteExpense,
    settleExpenseSplit,
  } = expensesStore

  // Keep backward-compatible API
  async function getExpense(id: number) {
    // Directly call service – rare use outside store
    return await import('@/services/expenseService').then(m => m.expenseService.getExpense(id))
  }

  return {
    expenses,
    recurringExpenses,
    loading,
    error,
    fetchExpenses,
    createExpense: createExpense as (data: CreateExpenseData) => Promise<any>,
    updateExpense: updateExpense as (id: number, data: UpdateExpenseData) => Promise<any>,
    deleteExpense,
    settleExpenseSplit: settleExpenseSplit as (expense_split_id: number, activity: SettlementActivityCreate) => Promise<void>,
    getExpense,
  }
}
