import { api } from './api'
import type {
  Expense,
  ExpenseCreate,
  ExpenseUpdate,
  Settlement,
  SettlementCreate,
  SettlementUpdate,
  SettlementActivity,
  SettlementActivityCreate,
  UserFinancialSummary,
  FinancialActivity,
  FinancialAuditLog,
} from '@/types/expense'
import type {
  Expense as UnifiedExpense,
  ExpenseCreate as UnifiedExpenseCreate,
  ExpenseUpdate as UnifiedExpenseUpdate
} from '@/types/unified-expense'

// Legacy types for backward compatibility
export interface CreateExpenseData {
  description: string
  total_amount: number
  currency?: string
  expense_date?: string
  split_type: string
  list_id?: number
  group_id?: number
  item_id?: number
  paid_by_user_id: number
  isRecurring?: boolean
  splits_in?: Array<{
    user_id: number
    owed_amount?: number
    share_percentage?: number
    share_units?: number
  }>
}

export interface UpdateExpenseData {
  description?: string
  total_amount?: number
  currency?: string
  expense_date?: string
  split_type?: string
  list_id?: number
  group_id?: number
  item_id?: number
  version: number
  isRecurring?: boolean
}

// Convert legacy expense format to unified format
function convertToUnified(expense: any): UnifiedExpense {
  return {
    id: expense.id,
    description: expense.description,
    total_amount: expense.total_amount,
    currency: expense.currency,
    expense_date: expense.expense_date,
    split_type: expense.split_type,
    list_id: expense.list_id,
    group_id: expense.group_id,
    item_id: expense.item_id,
    paid_by_user_id: expense.paid_by_user_id,
    paid_by_user: expense.paid_by_user,
    created_by_user_id: expense.created_by_user_id,
    created_by_user: expense.created_by_user,
    created_at: expense.created_at,
    updated_at: expense.updated_at,
    version: expense.version,
    splits: expense.splits || [],
    overall_settlement_status: expense.overall_settlement_status,
    is_recurring: expense.is_recurring || expense.isRecurring || false,
    next_occurrence: expense.next_occurrence || expense.nextOccurrence,
    last_occurrence: expense.last_occurrence || expense.lastOccurrence,
    recurrence_pattern: expense.recurrence_pattern || expense.recurrencePattern,
    parent_expense_id: expense.parent_expense_id || expense.parentExpenseId,
  }
}

// Convert unified format to legacy API format for creation
function convertToLegacyCreate(expense: UnifiedExpenseCreate): any {
  return {
    description: expense.description,
    total_amount: expense.total_amount,
    currency: expense.currency,
    expense_date: expense.expense_date,
    split_type: expense.split_type,
    list_id: expense.list_id,
    group_id: expense.group_id,
    item_id: expense.item_id,
    paid_by_user_id: expense.paid_by_user_id,
    is_recurring: expense.is_recurring,
    recurrence_pattern: expense.recurrence_pattern,
    splits_in: expense.splits_in,
  }
}

// Convert unified format to legacy API format for updates
function convertToLegacyUpdate(expense: UnifiedExpenseUpdate): any {
  return {
    description: expense.description,
    currency: expense.currency,
    expense_date: expense.expense_date,
    version: expense.version,
  }
}

export const expenseService = {
  // Expense CRUD operations
  async getExpenses(params?: {
    group_id?: number;
    list_id?: number;
    isRecurring?: boolean;
    skip?: number;
    limit?: number;
  }): Promise<UnifiedExpense[]> {
    const response = await api.get('/financials/expenses', { params })
    return response.data.map(convertToUnified)
  },

  async getExpense(id: number): Promise<UnifiedExpense> {
    const response = await api.get(`/financials/expenses/${id}`)
    return convertToUnified(response.data)
  },

  async createExpense(expenseData: UnifiedExpenseCreate): Promise<UnifiedExpense> {
    const legacyData = convertToLegacyCreate(expenseData)
    const response = await api.post('/financials/expenses', legacyData)
    return convertToUnified(response.data)
  },

  async updateExpense(id: number, updates: UnifiedExpenseUpdate): Promise<UnifiedExpense> {
    const legacyData = convertToLegacyUpdate(updates)
    const response = await api.put(`/financials/expenses/${id}`, legacyData)
    return convertToUnified(response.data)
  },

  async deleteExpense(id: number, expectedVersion?: number): Promise<void> {
    const params = expectedVersion ? { expected_version: expectedVersion } : undefined
    await api.delete(`/financials/expenses/${id}`, { params })
  },

  // Group expenses
  async getGroupExpenses(groupId: number, params?: { skip?: number; limit?: number }): Promise<UnifiedExpense[]> {
    const response = await api.get(`/financials/groups/${groupId}/expenses`, { params })
    return response.data.map(convertToUnified)
  },

  // Settlement Activity operations (for expense splits)
  async recordSettlementActivity(
    expenseSplitId: number,
    activity: SettlementActivityCreate
  ): Promise<SettlementActivity> {
    const response = await api.post(`/financials/expense_splits/${expenseSplitId}/settle`, activity)
    return response.data
  },

  async getSettlementActivitiesForSplit(
    expenseSplitId: number,
    params?: { skip?: number; limit?: number }
  ): Promise<SettlementActivity[]> {
    const response = await api.get(`/financials/expense_splits/${expenseSplitId}/settlement_activities`, { params })
    return response.data
  },

  // Generic Settlement operations
  async createSettlement(settlement: SettlementCreate): Promise<Settlement> {
    const response = await api.post('/financials/settlements', settlement)
    return response.data
  },

  async getSettlement(id: number): Promise<Settlement> {
    const response = await api.get(`/financials/settlements/${id}`)
    return response.data
  },

  async updateSettlement(id: number, updates: SettlementUpdate): Promise<Settlement> {
    const response = await api.put(`/financials/settlements/${id}`, updates)
    return response.data
  },

  async deleteSettlement(id: number, expectedVersion?: number): Promise<void> {
    const params = expectedVersion ? { expected_version: expectedVersion } : undefined
    await api.delete(`/financials/settlements/${id}`, { params })
  },

  async getGroupSettlements(groupId: number, params?: { skip?: number; limit?: number }): Promise<Settlement[]> {
    const response = await api.get(`/financials/groups/${groupId}/settlements`, { params })
    return response.data
  },

  // Financial Summary operations
  async getUserFinancialActivity(): Promise<FinancialActivity> {
    const response = await api.get('/financials/users/me/financial-activity')
    return response.data
  },

  async getUserFinancialSummary(): Promise<UserFinancialSummary> {
    const response = await api.get('/financials/summary/user')
    return response.data
  },

  async getGroupFinancialSummary(groupId: number): Promise<UserFinancialSummary> {
    const response = await api.get(`/financials/summary/group/${groupId}`)
    return response.data
  },

  // Financial History/Audit operations
  async getFinancialHistoryForGroup(
    groupId: number,
    params?: { skip?: number; limit?: number }
  ): Promise<FinancialAuditLog[]> {
    const response = await api.get(`/history/financial/group/${groupId}`, { params })
    return response.data
  },

  async getFinancialHistoryForUser(
    params?: { skip?: number; limit?: number }
  ): Promise<FinancialAuditLog[]> {
    const response = await api.get('/history/financial/user/me', { params })
    return response.data
  },

  // Legacy compatibility methods
  async settleExpenseSplit(
    expenseId: number,
    splitId: number,
    amount: string
  ): Promise<SettlementActivity> {
    const response = await api.post(`/financials/expense_splits/${splitId}/settle`, {
      expense_split_id: splitId,
      paid_by_user_id: 0, // Will need to be provided by caller
      amount_paid: amount
    })
    return response.data
  }
}
