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

/**
 * Get all workflows for a user
 * WU-18: Workflows domain
 */
export const getWorkflows = query({
  args: {
    userId: v.string(),
    status: v.optional(v.string()),
    limit: v.optional(v.number()),
  },
  handler: async (ctx, args) => {
    const limit = args.limit ?? 50;
    const q = ctx.db
      .query("user_workflows")
      .withIndex("by_userId_workflowType", (q) => q.eq("userId", args.userId));

    const results = await q.order("desc").take(limit);

    if (args.status) {
      return results.filter((r) => r.status === args.status);
    }

    return results;
  },
});

/**
 * Get a single workflow by ID
 * WU-18: Workflows domain
 */
export const getWorkflowById = query({
  args: {
    id: v.id("user_workflows"),
  },
  handler: async (ctx, args) => {
    return await ctx.db.get(args.id);
  },
});

/**
 * Get workflow executions for a workflow
 * WU-18: Workflows domain
 */
export const getExecutions = query({
  args: {
    workflowId: v.string(),
    limit: v.optional(v.number()),
  },
  handler: async (ctx, args) => {
    const limit = args.limit ?? 50;
    // Query all workflows and filter by workflowId
    // (execution tracking uses the workflow's fields directly)
    const workflow = await ctx.db
      .query("user_workflows")
      .filter((q) => q.eq(q.field("_id"), args.workflowId))
      .first();

    if (!workflow) return [];

    // Execution data is stored on the workflow itself (lastRunAt, lastRunStatus)
    return [
      {
        workflowId: workflow._id,
        status: workflow.lastRunStatus,
        runAt: workflow.lastRunAt,
        healthStatus: workflow.healthStatus,
        errorCount: workflow.errorCount,
      },
    ];
  },
});

/**
 * Get pending jobs from the job queue
 * WU-18: Workflows domain (job-worker cron)
 */
export const getPendingJobs = query({
  args: {
    limit: v.optional(v.number()),
  },
  handler: async (ctx, args) => {
    const limit = args.limit ?? 50;
    const now = Date.now();

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