/**
 * Expenses Service
 *
 * Thin service layer over the expenses adapter.
 * Expenses exist only in Convex (no Prisma tables).
 */

import { expensesAdapter, expenseCategoriesAdapter } from '@/lib/adapters/expenses';

export interface ExpenseFilters {
  categoryId?: string;
  startDate?: string;
  endDate?: string;
  minAmount?: number;
  maxAmount?: number;
}

export interface CreateExpenseInput {
  categoryId: string;
  amount: number;
  currency?: string;
  vendor?: string;
  description?: string;
  date: string | Date;
  receiptUrl?: string;
  isRecurring?: boolean;
  recurringFrequency?: string;
  tags?: string[];
  notes?: string;
}

export async function listExpenses(
  userId: string,
  filters: ExpenseFilters = {},
) {
  const where: Record<string, unknown> = { userId };
  if (filters.categoryId) {
    where.categoryId = filters.categoryId;
  }

  const expenses = await expensesAdapter.findMany({ where, take: 50 });
  const total = expenses.length;

  return { expenses, total };
}

export async function createExpense(
  userId: string,
  data: CreateExpenseInput,
) {
  const expense = await expensesAdapter.create({
    data: { userId, ...data },
  });
  return expense;
}

export async function getExpenseById(userId: string, id: string) {
  const expense = await expensesAdapter.findUnique({ where: { id } });
  return expense;
}

export async function deleteExpense(userId: string, id: string) {
  return expensesAdapter.delete({ where: { id } });
}

export async function listCategories(userId: string) {
  return expenseCategoriesAdapter.findMany({ where: { userId } });
}
