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

export const listGames = query({
  args: {
    search: v.optional(v.string()),
    tag: v.optional(v.string()),
    paginationOpts: paginationOptsValidator,
  },
  handler: async (ctx, { search, tag, paginationOpts }) => {
    let q = ctx.db.query("games").withIndex("by_published");

    const page = await q.order("desc").paginate(paginationOpts);

    // light-weight in-memory filtering for demo (replace w/ indexed search later)
    const filtered = page.page.filter((g) => {
      if (g.visibility !== "public") return false;
      if (tag && !(g.tags ?? []).includes(tag)) return false;
      if (
        search &&
        !`${g.title} ${g.description ?? ""}`
          .toLowerCase()
          .includes(search.toLowerCase())
      )
        return false;
      return true;
    });

    return { ...page, page: filtered };
  },
});

export const recordRunStart = mutation({
  args: { gameId: v.id("games"), playerId: v.optional(v.string()) },
  handler: async (ctx, { gameId, playerId }) => {
    const runId = await ctx.db.insert("runs", {
      gameId,
      playerId,
      startedAt: Date.now(),
    });

    // Increment play count
    const game = await ctx.db.get(gameId);
    if (game) {
      await ctx.db.patch(gameId, { plays: game.plays + 1 });
    }

    return runId;
  },
});

export const recordRunEnd = mutation({
  args: {
    runId: v.id("runs"),
    score: v.optional(v.number()),
    detail: v.optional(v.any()),
  },
  handler: async (ctx, { runId, score, detail }) => {
    await ctx.db.patch(runId, { endedAt: Date.now(), score, detail });
    return true;
  },
});

export const incrementLikes = mutation({
  args: { gameId: v.id("games") },
  handler: async (ctx, { gameId }) => {
    const game = await ctx.db.get(gameId);
    if (!game) throw new Error("Game not found");

    await ctx.db.patch(gameId, { likes: game.likes + 1 });
    return game.likes + 1;
  },
});
