import { authTables } from "@convex-dev/auth/server";
import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values";

export default defineSchema({
  ...authTables,
  creators: defineTable({
    handle: v.string(), // unique-ish public handle e.g., "@beatsby..."
    displayName: v.string(),
    avatarUrl: v.optional(v.string()),
    bio: v.optional(v.string()),
    // onboarding/provenance fields if you later add auth
    userId: v.optional(v.string()), // external auth user id
  })
    .index("by_handle", ["handle"])
    .index("by_userId", ["userId"]),

  games: defineTable({
    title: v.string(),
    slug: v.string(), // URL slug (unique)
    description: v.optional(v.string()),
    coverUrl: v.optional(v.string()), // square cover for feed
    /**
     * Where is the minigame hosted? Options:
     * - external: fully-qualified URL you or creators provide
     * - vercel-static: path we serve within Next static (e.g., /games/<slug>/index.html)
     */
    runtime: v.union(v.literal("external"), v.literal("vercel-static")),
    srcUrl: v.string(), // iframe src we embed

    tags: v.optional(v.array(v.string())),
    creatorId: v.id("creators"),

    // moderation & status
    visibility: v.union(
      v.literal("public"),
      v.literal("unlisted"),
      v.literal("private")
    ),
    publishedAt: v.number(), // Date.now()

    // simple rating/engagement counters (you may denormalize later)
    plays: v.number(),
    likes: v.number(),
  })
    .index("by_published", ["publishedAt"])
    .index("by_slug", ["slug"])
    .index("by_creator", ["creatorId"]),

  runs: defineTable({
    gameId: v.id("games"),
    // optional player identity
    playerId: v.optional(v.string()),
    // ephemeral run state & score payloads
    startedAt: v.number(),
    endedAt: v.optional(v.number()),
    score: v.optional(v.number()),
    // raw detail to evolve later (JSON blob from game)
    detail: v.optional(v.any()),
  })
    .index("by_game", ["gameId"])
    .index("by_player", ["playerId"]),
});
