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

/**
 * Create a new waitlist
 */
export const createWaitlist = mutation({
  args: {
    title: v.string(),
    titleAr: v.optional(v.string()),
    description: v.optional(v.string()),
    descriptionAr: v.optional(v.string()),
    category: v.string(),
    isActive: v.boolean(),
    isPublic: v.boolean(),
    userId: v.optional(v.string()),
    createdBy: v.string(),
  },
  handler: async (ctx, args) => {
    const now = Date.now();
    return await ctx.db.insert("waitlists", {
      title: args.title,
      titleAr: args.titleAr,
      description: args.description,
      descriptionAr: args.descriptionAr,
      category: args.category,
      isActive: args.isActive,
      isPublic: args.isPublic,
      userId: args.userId,
      createdBy: args.createdBy,
      createdAt: now,
      updatedAt: now,
    });
  },
});

/**
 * Update a waitlist
 */
export const updateWaitlist = mutation({
  args: {
    id: v.id("waitlists"),
    title: v.optional(v.string()),
    titleAr: v.optional(v.string()),
    description: v.optional(v.string()),
    descriptionAr: v.optional(v.string()),
    category: v.optional(v.string()),
    isActive: v.optional(v.boolean()),
    isPublic: v.optional(v.boolean()),
  },
  handler: async (ctx, args) => {
    const { id, ...fields } = args;
    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 waitlist
 */
export const deleteWaitlist = mutation({
  args: { id: v.id("waitlists") },
  handler: async (ctx, args) => {
    await ctx.db.delete(args.id);
    return { deleted: true };
  },
});

/**
 * Create a waitlist signup
 */
export const createSignup = mutation({
  args: {
    waitlistId: v.string(),
    userId: v.optional(v.string()),
    name: v.string(),
    email: v.string(),
    mobile: v.string(),
    notes: v.optional(v.string()),
    addedBy: v.optional(v.string()),
  },
  handler: async (ctx, args) => {
    const now = Date.now();
    return await ctx.db.insert("waitlist_signups", {
      waitlistId: args.waitlistId,
      userId: args.userId,
      name: args.name,
      email: args.email.toLowerCase(),
      mobile: args.mobile,
      notes: args.notes,
      addedBy: args.addedBy,
      createdAt: now,
    });
  },
});

/**
 * Delete a waitlist signup
 */
export const deleteSignup = mutation({
  args: { id: v.id("waitlist_signups") },
  handler: async (ctx, args) => {
    await ctx.db.delete(args.id);
    return { deleted: true };
  },
});
