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

// List all categories ordered by position
export const list = query({
  args: {},
  returns: v.array(
    v.object({
      _id: v.id("categories"),
      _creationTime: v.number(),
      name: v.string(),
      position: v.number(),
    })
  ),
  handler: async (ctx) => {
    return await ctx.db
      .query("categories")
      .withIndex("by_position")
      .collect();
  },
});

// Create a new category
export const create = mutation({
  args: { name: v.string() },
  returns: v.object({ id: v.id("categories") }),
  handler: async (ctx, args) => {
    const name = args.name.trim();
    if (!name) throw new Error("Category name required");

    // Auto-assign position at end
    const all = await ctx.db.query("categories").collect();
    const maxPos = all.reduce((max, c) => Math.max(max, c.position), -1000);

    const id = await ctx.db.insert("categories", {
      name,
      position: maxPos + 1000,
    });
    return { id };
  },
});

// Rename a category
export const rename = mutation({
  args: {
    id: v.id("categories"),
    name: v.string(),
  },
  returns: v.null(),
  handler: async (ctx, args) => {
    const name = args.name.trim();
    if (!name) throw new Error("Category name required");
    const cat = await ctx.db.get(args.id);
    if (!cat) throw new Error("Category not found");
    await ctx.db.patch(args.id, { name });
    return null;
  },
});

// Delete a category (moves its channels to uncategorized)
export const remove = mutation({
  args: { id: v.id("categories") },
  returns: v.null(),
  handler: async (ctx, args) => {
    const cat = await ctx.db.get(args.id);
    if (!cat) throw new Error("Category not found");

    // Move channels to uncategorized
    const channels = await ctx.db
      .query("channels")
      .withIndex("by_category", (q) => q.eq("categoryId", args.id))
      .collect();
    for (const ch of channels) {
      await ctx.db.patch(ch._id, { categoryId: undefined });
    }

    await ctx.db.delete(args.id);
    return null;
  },
});

// Batch reorder categories
export const reorder = mutation({
  args: {
    updates: v.array(
      v.object({
        id: v.id("categories"),
        position: v.number(),
      })
    ),
  },
  returns: v.null(),
  handler: async (ctx, args) => {
    for (const u of args.updates) {
      await ctx.db.patch(u.id, { position: u.position });
    }
    return null;
  },
});
