import { query } from "../_generated/server";
import { v } from "convex/values";

/**
 * Get expenses for a user (paginated, optionally filtered by category/date)
 * Phase 7: Leads, Quotations, Expenses
 */
export const getExpenses = query({
  args: {
    userId: v.string(),
    categoryId: v.optional(v.string()),
    limit: v.optional(v.number()),
  },
  handler: async (ctx, args) => {
    const limit = args.limit ?? 50;
    const q = ctx.db
      .query("expenses")
      .withIndex("by_userId", (q) => q.eq("userId", args.userId));

    if (args.categoryId) {
      return await q
        .filter((f) => f.eq(f.field("categoryId"), args.categoryId))
        .order("desc")
        .take(limit);
    }

    return await q.order("desc").take(limit);
  },
});

/**
 * Get expense categories for a user
 * Phase 7: Leads, Quotations, Expenses
 */
export const getCategories = query({
  args: { userId: v.string() },
  handler: async (ctx, args) => {
    return await ctx.db
      .query("expense_categories")
      .withIndex("by_userId_sortOrder", (q) => q.eq("userId", args.userId))
      .collect();
  },
});
