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

// ── Enums ──────────────────────────────────────────────────────────────

export const userLinkTypeValidator = v.union(
  v.literal("KNOWLEDGE_BASE"),
  v.literal("AI_AGENT"),
  v.literal("AI_VOICE_AGENT"),
  v.literal("WHATSAPP_INTEGRATION"),
  v.literal("DASHBOARD"),
  v.literal("DOCUMENTATION"),
  v.literal("SUPPORT"),
  v.literal("CUSTOM"),
  v.literal("APPOINTMENTS"),
  v.literal("CUSTOMERS"),
  v.literal("WAITLISTS"),
  v.literal("ANALYTICS"),
  v.literal("BILLING"),
  v.literal("SETTINGS"),
  v.literal("CALENDAR"),
  v.literal("REPORTS"),
);

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

export const workflowTables = {
  user_workflows: defineTable({
    prismaId: v.optional(v.string()),
    userId: v.string(),
    workflowType: v.string(),
    n8nWorkflowId: v.optional(v.string()),
    status: v.string(),
    config: v.any(),
    lastRunAt: v.optional(v.number()),
    lastRunStatus: v.optional(v.string()),
    createdAt: v.number(),
    updatedAt: v.number(),
    errorCount: v.number(),
    healthStatus: v.string(),
    lastErrorAt: v.optional(v.number()),
  })
    .index("by_healthStatus", ["healthStatus"])
    .index("by_status", ["status"])
    .index("by_userId_workflowType", ["userId", "workflowType"]),

  user_api_keys: defineTable({
    prismaId: v.optional(v.string()),
    userId: v.string(),
    service: v.string(),
    keyName: v.string(),
    encryptedKey: v.string(),
    isActive: v.boolean(),
    expiresAt: v.optional(v.number()),
    lastUsedAt: v.optional(v.number()),
    createdAt: v.number(),
    updatedAt: v.number(),
  })
    .index("by_userId_isActive", ["userId", "isActive"])
    .index("by_userId_service_keyName", ["userId", "service", "keyName"]),

  user_links: defineTable({
    prismaId: v.optional(v.string()),
    userId: v.string(),
    linkType: userLinkTypeValidator,
    title: v.string(),
    url: v.string(),
    description: v.optional(v.string()),
    icon: v.optional(v.string()),
    isActive: v.boolean(),
    sortOrder: v.number(),
    createdBy: v.string(),
    updatedBy: v.optional(v.string()),
    createdAt: v.number(),
    updatedAt: v.number(),
  })
    .index("by_createdAt", ["createdAt"])
    .index("by_userId_isActive", ["userId", "isActive"])
    .index("by_userId_linkType", ["userId", "linkType"]),
};
