import type { Expense, RecurrencePattern } from '@/types/expense'
import { api, API_ENDPOINTS } from '@/services/api'

export interface CreateExpenseData {
  description: string
  total_amount: string
  currency: string
  split_type: string
  isRecurring: boolean
  recurrencePattern?: {
    type: 'daily' | 'weekly' | 'monthly' | 'yearly'
    interval: number
    daysOfWeek?: number[]
    endDate?: string
    maxOccurrences?: number
  }
  list_id?: number
  group_id?: number
  item_id?: number
  paid_by_user_id: number
  splits_in?: Array<{
    user_id: number
    amount: string
    percentage?: number
    shares?: number
  }>
}

export interface UpdateExpenseData extends Partial<CreateExpenseData> {
  version: number
}

export const expenseService = {
  async createExpense(data: CreateExpenseData): Promise<Expense> {
    const response = await api.post<Expense>(API_ENDPOINTS.FINANCIALS.EXPENSES, data)
    return response.data
  },

  async updateExpense(id: number, data: UpdateExpenseData): Promise<Expense> {
    const response = await api.put<Expense>(API_ENDPOINTS.FINANCIALS.EXPENSE(id.toString()), data)
    return response.data
  },

  async deleteExpense(id: number): Promise<void> {
    await api.delete(API_ENDPOINTS.FINANCIALS.EXPENSE(id.toString()))
  },

  async getExpense(id: number): Promise<Expense> {
    const response = await api.get<Expense>(API_ENDPOINTS.FINANCIALS.EXPENSE(id.toString()))
    return response.data
  },

  async getExpenses(params?: {
    list_id?: number
    group_id?: number
    isRecurring?: boolean
  }): Promise<Expense[]> {
    const response = await api.get<Expense[]>(API_ENDPOINTS.FINANCIALS.EXPENSES, { params })
    return response.data
  },

  async getRecurringExpenses(): Promise<Expense[]> {
    return this.getExpenses({ isRecurring: true })
  },
}
