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

/**
 * Create a new expense record
 * Phase 7: Leads, Quotations, Expenses
 */
export const createExpense = mutation({
  args: {
    userId: v.string(),
    categoryId: v.string(),
    amount: v.number(),
    currency: v.optional(v.string()),
    vendor: v.optional(v.string()),
    description: v.optional(v.string()),
    date: v.number(),
    receiptUrl: v.optional(v.string()),
    isRecurring: v.optional(v.boolean()),
    recurringFrequency: v.optional(v.string()),
    tags: v.optional(v.array(v.string())),
    notes: v.optional(v.string()),
  },
  handler: async (ctx, args) => {
    const now = Date.now();
    const id = await ctx.db.insert("expenses", {
      userId: args.userId,
      categoryId: args.categoryId,
      amount: args.amount,
      currency: args.currency ?? "QAR",
      vendor: args.vendor,
      description: args.description,
      date: args.date,
      receiptUrl: args.receiptUrl,
      isRecurring: args.isRecurring ?? false,
      recurringFrequency: args.recurringFrequency,
      tags: args.tags ?? [],
      notes: args.notes,
      createdAt: now,
      updatedAt: now,
    });
    return id;
  },
});

/**
 * Update an existing expense
 * Phase 7: Leads, Quotations, Expenses
 */
export const updateExpense = mutation({
  args: {
    id: v.id("expenses"),
    categoryId: v.optional(v.string()),
    amount: v.optional(v.number()),
    vendor: v.optional(v.string()),
    description: v.optional(v.string()),
    date: v.optional(v.number()),
    receiptUrl: v.optional(v.string()),
    tags: v.optional(v.array(v.string())),
    notes: v.optional(v.string()),
  },
  handler: async (ctx, args) => {
    const existing = await ctx.db.get(args.id);
    if (!existing) {
      throw new Error(`Expense ${args.id} not found`);
    }
    const { id, ...fields } = args;
    const patch: Record<string, unknown> = { updatedAt: Date.now() };
    for (const [key, value] of Object.entries(fields)) {
      if (value !== undefined) patch[key] = value;
    }
    await ctx.db.patch(id, patch);
    return id;
  },
});

/**
 * Delete an expense record
 * Phase 7: Leads, Quotations, Expenses
 */
export const deleteExpense = mutation({
  args: { id: v.id("expenses") },
  handler: async (ctx, args) => {
    const existing = await ctx.db.get(args.id);
    if (!existing) {
      throw new Error(`Expense ${args.id} not found`);
    }
    await ctx.db.delete(args.id);
    return args.id;
  },
});

/**
 * Create an expense category
 * Phase 7: Leads, Quotations, Expenses
 */
export const createCategory = mutation({
  args: {
    userId: v.string(),
    name: v.string(),
    nameAr: v.optional(v.string()),
    color: v.string(),
    icon: v.optional(v.string()),
    sortOrder: v.optional(v.number()),
  },
  handler: async (ctx, args) => {
    const now = Date.now();
    const id = await ctx.db.insert("expense_categories", {
      userId: args.userId,
      name: args.name,
      nameAr: args.nameAr,
      color: args.color,
      icon: args.icon,
      sortOrder: args.sortOrder ?? 0,
      createdAt: now,
      updatedAt: now,
    });
    return id;
  },
});
