import { query } from "./_generated/server";
import { v } from "convex/values";
import { requireUserId } from "./_utils/auth";
import { nowIso } from "./_utils/time";

async function requireWorkspaceMember(ctx: any, workspaceId: string, userId: string) {
  const member = await ctx.db
    .query("workspace_members")
    .withIndex("by_workspace_user", (q: any) => q.eq("workspace_id", workspaceId).eq("user_id", userId))
    .first();
  if (!member) {
    throw new Error("无权限");
  }
  return member;
}

export const listByTrace = query({
  args: { workspaceId: v.string(), traceId: v.string() },
  handler: async (ctx, args) => {
    const userId = await requireUserId(ctx);
    await requireWorkspaceMember(ctx, args.workspaceId, userId);

    const commandLogs = await ctx.db
      .query("command_logs")
      .withIndex("by_workspace_trace", (q) => q.eq("workspace_id", args.workspaceId).eq("trace_id", args.traceId))
      .collect();
    const domainEvents = await ctx.db
      .query("domain_events")
      .withIndex("by_workspace_trace", (q) => q.eq("workspace_id", args.workspaceId).eq("trace_id", args.traceId))
      .collect();

    return {
      trace_id: args.traceId,
      command_logs: commandLogs,
      domain_events: domainEvents,
      generated_at: nowIso(),
    };
  },
});

export const listByRequest = query({
  args: { workspaceId: v.string(), requestId: v.string() },
  handler: async (ctx, args) => {
    const userId = await requireUserId(ctx);
    await requireWorkspaceMember(ctx, args.workspaceId, userId);

    const commandLogs = await ctx.db
      .query("command_logs")
      .withIndex("by_workspace_request", (q) => q.eq("workspace_id", args.workspaceId).eq("request_id", args.requestId))
      .collect();
    const domainEvents = await ctx.db
      .query("domain_events")
      .withIndex("by_workspace_request", (q) => q.eq("workspace_id", args.workspaceId).eq("request_id", args.requestId))
      .collect();

    return {
      request_id: args.requestId,
      command_logs: commandLogs,
      domain_events: domainEvents,
      generated_at: nowIso(),
    };
  },
});
