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

/**
 * Bulk-create appointment types for an organization.
 * Used during onboarding to seed sector-specific service catalogues.
 */
export const createBulk = mutation({
  args: {
    organizationId: v.string(),
    types: v.array(
      v.object({
        nameEn: v.string(),
        nameAr: v.string(),
        duration: v.number(),
        price: v.optional(v.number()),
        category: v.optional(v.string()),
        categoryAr: v.optional(v.string()),
        itemType: v.optional(v.string()),
        isActive: v.boolean(),
        sortOrder: v.number(),
      }),
    ),
  },
  handler: async (ctx, args) => {
    const now = Date.now();
    let count = 0;

    for (const typeData of args.types) {
      await ctx.db.insert("appointment_types", {
        organizationId: args.organizationId,
        nameEn: typeData.nameEn,
        nameAr: typeData.nameAr,
        duration: typeData.duration,
        price: typeData.price,
        category: typeData.category,
        categoryAr: typeData.categoryAr,
        itemType: typeData.itemType,
        isActive: typeData.isActive,
        sortOrder: typeData.sortOrder,
        createdAt: now,
        updatedAt: now,
      });
      count++;
    }

    return { count };
  },
});

/**
 * Update the itemType field on an existing appointment type.
 * Useful for back-filling legacy records with sector metadata.
 */
export const updateItemType = mutation({
  args: {
    id: v.id("appointment_types"),
    itemType: v.optional(v.string()),
  },
  handler: async (ctx, args) => {
    const existing = await ctx.db.get(args.id);
    if (!existing) {
      throw new Error(`Appointment type ${args.id} not found`);
    }

    await ctx.db.patch(args.id, {
      itemType: args.itemType,
      updatedAt: Date.now(),
    });

    return args.id;
  },
});
