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

/**
 * Get pending sync tasks from the queue
 * WU-18: Sync domain
 */
export const getPendingSyncTasks = query({
  args: {
    limit: v.optional(v.number()),
  },
  handler: async (ctx, args) => {
    const limit = args.limit ?? 100;
    const now = Date.now();

    return await ctx.db
      .query("sync_queue")
      .withIndex("by_nextRetryAt_attempts", (q) => q.lte("nextRetryAt", now))
      .take(limit);
  },
});

/**
 * Get overall sync status (metrics)
 * WU-18: Sync domain
 */
export const getSyncStatus = query({
  args: {},
  handler: async (ctx) => {
    const now = Date.now();

    // Get pending tasks
    const pendingTasks = await ctx.db
      .query("sync_queue")
      .withIndex("by_nextRetryAt_attempts", (q) => q.lte("nextRetryAt", now))
      .collect();

    // Get total queue size
    const allTasks = await ctx.db.query("sync_queue").collect();

    // Get DLQ items
    const dlqItems = await ctx.db.query("sync_queue_dlq").collect();

    // Get failed tasks (attempts > 0)
    const failedTasks = allTasks.filter((t) => t.attempts > 0);

    return {
      pending: pendingTasks.length,
      total: allTasks.length,
      failed: failedTasks.length,
      dlqCount: dlqItems.length,
      status:
        dlqItems.length > 10
          ? "degraded"
          : allTasks.length > 1000
            ? "degraded"
            : "healthy",
    };
  },
});
