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

/**
 * Create a new customer
 * Group B: Customers domain migration
 */
export const createCustomer = mutation({
  args: {
    userId: v.string(),
    organizationId: v.optional(v.string()),
    name: v.string(),
    phone: v.string(),
    email: v.optional(v.string()),
    notes: v.optional(v.string()),
    source: v.optional(v.string()),
  },
  handler: async (ctx, args) => {
    // Duplicate phone check within the same user/org scope
    const existing = await ctx.db
      .query("customers")
      .withIndex("by_userId_phone", (q) =>
        q.eq("userId", args.userId).eq("phone", args.phone),
      )
      .first();
    if (existing) throw new Error("DUPLICATE_PHONE");

    const now = Date.now();
    return await ctx.db.insert("customers", {
      userId: args.userId,
      organizationId: args.organizationId,
      name: args.name,
      phone: args.phone,
      email: args.email,
      notes: args.notes,
      source: args.source,
      createdAt: now,
      updatedAt: now,
    });
  },
});

/**
 * Update an existing customer
 * Group B: Customers domain migration
 */
export const updateCustomer = mutation({
  args: {
    id: v.id("customers"),
    userId: v.string(),
    name: v.optional(v.string()),
    phone: v.optional(v.string()),
    email: v.optional(v.string()),
    notes: v.optional(v.string()),
    source: v.optional(v.string()),
  },
  handler: async (ctx, { id, userId, ...fields }) => {
    const customer = await ctx.db.get(id);
    if (!customer || customer.userId !== userId) throw new Error("NOT_FOUND");

    const updates: Record<string, unknown> = { updatedAt: Date.now() };
    for (const [key, value] of Object.entries(fields)) {
      if (value !== undefined) {
        updates[key] = value;
      }
    }
    await ctx.db.patch(id, updates);
    return await ctx.db.get(id);
  },
});

/**
 * Delete a customer
 * Group B: Customers domain migration
 */
export const deleteCustomer = mutation({
  args: { id: v.id("customers"), userId: v.string() },
  handler: async (ctx, { id, userId }) => {
    const customer = await ctx.db.get(id);
    if (!customer || customer.userId !== userId) throw new Error("NOT_FOUND");
    await ctx.db.delete(id);
    return { deleted: true };
  },
});
