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

export const seedGame = mutation({
  args: {
    title: v.string(),
    slug: v.string(),
    srcUrl: v.string(),
    runtime: v.union(v.literal("external"), v.literal("vercel-static")),
    coverUrl: v.optional(v.string()),
    description: v.optional(v.string()),
    tags: v.optional(v.array(v.string())),
  },
  handler: async (ctx, args) => {
    // simple creator for demo
    const [creator] = await ctx.db
      .query("creators")
      .withIndex("by_handle", (q) => q.eq("handle", "@system"))
      .collect();

    const creatorId =
      creator?._id ??
      (await ctx.db.insert("creators", {
        handle: "@system",
        displayName: "System",
      }));

    return await ctx.db.insert("games", {
      title: args.title,
      slug: args.slug,
      srcUrl: args.srcUrl,
      runtime: args.runtime,
      coverUrl: args.coverUrl,
      description: args.description,
      tags: args.tags,
      creatorId,
      visibility: "public",
      publishedAt: Date.now(),
      plays: 0,
      likes: 0,
    });
  },
});

export const clearAllGames = mutation({
  handler: async (ctx) => {
    const games = await ctx.db.query("games").collect();
    for (const game of games) {
      await ctx.db.delete(game._id);
    }
    return { deleted: games.length };
  },
});
