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

export const ensureDefaults = mutation({
  args: { tenantId: v.string() },
  handler: async (ctx, { tenantId }) => {
    let existing = await ctx.db
      .query("queues")
      .withIndex("by_tenant", (q) => q.eq("tenantId", tenantId))
      .take(10);
    existing = await Promise.all(
      existing.map(async (queue) => {
        if (queue.name === "Suporte N1" || queue.slug === "suporte-n1") {
          await ctx.db.patch(queue._id, { name: "Chamados", slug: "chamados" });
          return (await ctx.db.get(queue._id)) ?? queue;
        }
        if (queue.name === "Suporte N2" || queue.slug === "suporte-n2") {
          await ctx.db.patch(queue._id, { name: "Laboratório", slug: "laboratorio" });
          return (await ctx.db.get(queue._id)) ?? queue;
        }
        if (queue.name === "Field Services" || queue.slug === "field-services") {
          await ctx.db.patch(queue._id, { name: "Visitas", slug: "visitas" });
          return (await ctx.db.get(queue._id)) ?? queue;
        }
        return queue;
      })
    );
    if (existing.length === 0) {
      const queues = [
        { name: "Chamados", slug: "chamados" },
        { name: "Laboratório", slug: "laboratorio" },
        { name: "Visitas", slug: "visitas" },
      ];
      for (const q of queues) {
        await ctx.db.insert("queues", { tenantId, name: q.name, slug: q.slug, teamId: undefined });
      }
    }
  },
});
