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

// Use anyApi to reference functions not yet in generated types.
// After running `npx convex dev`, switch to `import { api } from "../_generated/api"`.
const typedApi = anyApi as Record<
  string,
  Record<string, Record<string, unknown>>
>;

/**
 * Provision core appointment types for a new organization.
 *
 * Called during onboarding after the org is created.  Skips if the org
 * already has at least one appointment type (idempotent).
 */
export const provisionCoreTypes = action({
  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()),
      }),
    ),
  },
  handler: async (ctx, args) => {
    // Check if org already has appointment types (idempotent)
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const existing = await ctx.runQuery(
      typedApi.appointment_types.queries.getByOrganization as any,
      { organizationId: args.organizationId },
    );

    if (existing && (existing as unknown[]).length > 0) {
      return { created: 0, skipped: true };
    }

    // Create each type sequentially (maintains sort order)
    let created = 0;
    for (const [index, type] of args.types.entries()) {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      await ctx.runMutation(
        typedApi.appointment_types.mutations.create as any,
        {
          organizationId: args.organizationId,
          ...type,
          isActive: true,
          sortOrder: index,
        },
      );
      created++;
    }

    return { created, skipped: false };
  },
});
