import { defineTable } from "convex/server";
import { v } from "convex/values";

// ── Tables ─────────────────────────────────────────────────────────────

export const syncTables = {
  sync_queue: defineTable({
    prismaId: v.optional(v.string()),
    table: v.string(),
    operation: v.string(),
    data: v.any(),
    conflictColumn: v.string(),
    attempts: v.number(),
    maxAttempts: v.number(),
    lastError: v.optional(v.string()),
    nextRetryAt: v.number(),
    createdAt: v.number(),
  })
    .index("by_nextRetryAt_attempts", ["nextRetryAt", "attempts"])
    .index("by_table_createdAt", ["table", "createdAt"]),

  sync_queue_dlq: defineTable({
    prismaId: v.optional(v.string()),
    originalId: v.string(),
    table: v.string(),
    operation: v.string(),
    data: v.any(),
    conflictColumn: v.string(),
    attempts: v.number(),
    lastError: v.optional(v.string()),
    originalCreated: v.number(),
    movedToDlqAt: v.number(),
    replayedAt: v.optional(v.number()),
    replayStatus: v.optional(v.string()),
    reviewedAt: v.optional(v.number()),
    reviewedBy: v.optional(v.string()),
    resolution: v.optional(v.string()),
  })
    .index("by_table_movedToDlqAt", ["table", "movedToDlqAt"])
    .index("by_replayStatus", ["replayStatus"])
    .index("by_reviewedAt", ["reviewedAt"]),

  sync_queue_dlq_archive: defineTable({
    prismaId: v.optional(v.string()),
    originalId: v.string(),
    dlqId: v.string(),
    table: v.string(),
    operation: v.string(),
    data: v.any(),
    conflictColumn: v.string(),
    attempts: v.number(),
    lastError: v.optional(v.string()),
    originalCreated: v.number(),
    movedToDlqAt: v.number(),
    replayedAt: v.optional(v.number()),
    replayStatus: v.optional(v.string()),
    reviewedAt: v.optional(v.number()),
    reviewedBy: v.optional(v.string()),
    resolution: v.optional(v.string()),
    archivedAt: v.number(),
  })
    .index("by_table_archivedAt", ["table", "archivedAt"])
    .index("by_originalCreated", ["originalCreated"]),
};
