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

export const listByWorkspace = query({
  args: { userId: v.string(), workspaceId: v.string(), limit: v.optional(v.number()) },
  handler: async (ctx, args) => {
    const rows = await ctx.db
      .query("user_recent_pages")
      .withIndex("by_user_workspace", (q) => q.eq("user_id", args.userId).eq("workspace_id", args.workspaceId))
      .collect();

    const sorted = rows.sort((a, b) => (b.last_accessed_at ?? "").localeCompare(a.last_accessed_at ?? ""));
    const limit = Math.max(0, Math.min(args.limit ?? 10, 50));
    return sorted.slice(0, limit).map((r) => ({
      user_id: r.user_id,
      workspace_id: r.workspace_id,
      document_id: r.document_id,
      last_accessed_at: r.last_accessed_at,
    }));
  },
});

export const upsert = mutation({
  args: { userId: v.string(), workspaceId: v.string(), documentId: v.string(), lastAccessedAt: v.string() },
  handler: async (ctx, args) => {
    const existing = await ctx.db
      .query("user_recent_pages")
      .withIndex("by_user_document", (q) => q.eq("user_id", args.userId).eq("document_id", args.documentId))
      .first();

    if (existing) {
      await ctx.db.patch(existing._id, {
        workspace_id: args.workspaceId,
        last_accessed_at: args.lastAccessedAt,
      });
      return { ok: true, updated: true };
    }

    await ctx.db.insert("user_recent_pages", {
      user_id: args.userId,
      workspace_id: args.workspaceId,
      document_id: args.documentId,
      last_accessed_at: args.lastAccessedAt,
    });

    return { ok: true, updated: false };
  },
});

