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

/**
 * Get leads for a user (paginated)
 * Phase 7: Leads, Quotations, Expenses
 */
export const getLeads = query({
  args: {
    userId: v.string(),
    status: v.optional(v.string()),
    limit: v.optional(v.number()),
  },
  handler: async (ctx, args) => {
    const limit = args.limit ?? 50;
    return await ctx.db
      .query("leads")
      .withIndex("by_userId", (q) => q.eq("userId", args.userId))
      .order("desc")
      .take(limit);
  },
});

/**
 * Get a single lead by ID
 * Phase 7: Leads, Quotations, Expenses
 */
export const getById = query({
  args: { id: v.id("leads") },
  handler: async (ctx, args) => {
    return await ctx.db.get(args.id);
  },
});

/**
 * Get activity timeline for a lead
 * Phase 7: Leads, Quotations, Expenses
 */
export const getActivities = query({
  args: {
    leadId: v.string(),
    limit: v.optional(v.number()),
  },
  handler: async (ctx, args) => {
    const limit = args.limit ?? 50;
    return await ctx.db
      .query("lead_activities")
      .withIndex("by_leadId", (q) => q.eq("leadId", args.leadId))
      .order("desc")
      .take(limit);
  },
});

/**
 * Get pipeline stages for a user's Kanban board
 * Phase 7: Leads, Quotations, Expenses
 */
export const getPipelineStages = query({
  args: { userId: v.string() },
  handler: async (ctx, args) => {
    return await ctx.db
      .query("lead_pipeline_stages")
      .withIndex("by_userId_sortOrder", (q) => q.eq("userId", args.userId))
      .collect();
  },
});
