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

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

export const conversationStatusValidator = v.union(
  v.literal("active"),
  v.literal("resolved"),
  v.literal("escalated_to_human"),
  v.literal("abandoned"),
);

export const messageSenderValidator = v.union(
  v.literal("customer"),
  v.literal("ai_agent"),
  v.literal("admin"),
);

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

export const whatsappTables = {
  whatsapp_conversations: defineTable({
    prismaId: v.optional(v.string()),
    userId: v.string(),
    customerPhone: v.string(),
    customerName: v.optional(v.string()),
    lastMessage: v.optional(v.string()),
    lastMessageAt: v.optional(v.number()),
    status: conversationStatusValidator,
    tags: v.array(v.string()),
    aiActions: v.optional(v.any()),
    summary: v.optional(v.string()),
    bookingId: v.optional(v.string()),
    unreadCount: v.number(),
    createdAt: v.number(),
    updatedAt: v.number(),
  })
    .index("by_customerPhone", ["customerPhone"])
    .index("by_lastMessageAt", ["lastMessageAt"])
    .index("by_status", ["status"])
    .index("by_userId", ["userId"]),

  conversation_messages: defineTable({
    prismaId: v.optional(v.string()),
    conversationId: v.string(),
    sender: messageSenderValidator,
    message: v.string(),
    timestamp: v.number(),
    metadata: v.optional(v.any()),
  })
    .index("by_conversationId", ["conversationId"])
    .index("by_timestamp", ["timestamp"]),

  org_whatsapp_conversations: defineTable({
    prismaId: v.optional(v.string()),
    organizationId: v.string(),
    userPhone: v.string(),
    userName: v.optional(v.string()),
    language: v.string(),
    status: v.string(),
    lastMessageAt: v.optional(v.number()),
    messageCount: v.number(),
    conversationState: v.optional(v.any()),
    customerEmail: v.optional(v.string()),
    humanControlled: v.boolean(),
    humanControlledAt: v.optional(v.number()),
    humanControlledBy: v.optional(v.string()),
    createdAt: v.number(),
    updatedAt: v.number(),
  })
    .index("by_organizationId", ["organizationId"])
    .index("by_userPhone", ["userPhone"])
    .index("by_organizationId_userPhone", ["organizationId", "userPhone"])
    .index("by_organizationId_status", ["organizationId", "status"])
    .index("by_createdAt", ["createdAt"])
    .index("by_lastMessageAt", ["lastMessageAt"])
    .index("by_humanControlled", ["humanControlled"]),

  org_whatsapp_messages: defineTable({
    prismaId: v.optional(v.string()),
    conversationId: v.string(),
    role: v.string(),
    content: v.string(),
    language: v.string(),
    intent: v.optional(v.string()),
    toolsUsed: v.array(v.string()),
    metadata: v.optional(v.any()),
    timestamp: v.number(),
    // KB metadata fields
    kbUsed: v.optional(v.boolean()),
    kbConfidence: v.optional(v.number()),
    questionCategory: v.optional(v.string()),
    escalatedToHuman: v.optional(v.boolean()),
  })
    .index("by_conversationId", ["conversationId"])
    .index("by_conversationId_timestamp", ["conversationId", "timestamp"])
    .index("by_role", ["role"])
    .index("by_intent", ["intent"])
    .index("by_timestamp", ["timestamp"]),

  user_language_preferences: defineTable({
    prismaId: v.optional(v.string()),
    organizationId: v.string(),
    userPhone: v.string(),
    language: v.string(),
    selectedAt: v.number(),
    createdAt: v.number(),
    updatedAt: v.number(),
  })
    .index("by_userPhone", ["userPhone"])
    .index("by_organizationId", ["organizationId"])
    .index("by_organizationId_userPhone", ["organizationId", "userPhone"]),

  company_knowledge_base: defineTable({
    prismaId: v.optional(v.string()),
    organizationId: v.string(),
    question: v.string(),
    answer: v.string(),
    category: v.optional(v.string()),
    language: v.string(),
    embedding: v.optional(v.any()),
    isActive: v.boolean(),
    priority: v.number(),
    createdAt: v.number(),
    updatedAt: v.number(),
    createdBy: v.optional(v.string()),
  })
    .index("by_organizationId", ["organizationId"])
    .index("by_organizationId_language", ["organizationId", "language"])
    .index("by_organizationId_language_isActive", [
      "organizationId",
      "language",
      "isActive",
    ])
    .index("by_category", ["category"])
    .index("by_priority", ["priority"]),

  unanswered_questions: defineTable({
    organizationId: v.string(),
    question: v.string(),
    normalizedQuestion: v.optional(v.string()),
    frequency: v.number(),
    sector: v.optional(v.string()),
    language: v.string(),
    firstAskedAt: v.number(),
    lastAskedAt: v.number(),
    status: v.string(), // 'open' | 'suggested' | 'resolved'
    suggestedFaqId: v.optional(v.string()),
  })
    .index("by_organizationId", ["organizationId"])
    .index("by_organizationId_status", ["organizationId", "status"])
    .index("by_sector", ["sector"])
    .index("by_frequency", ["frequency"]),

  suggested_faqs: defineTable({
    organizationId: v.string(),
    question: v.string(),
    suggestedAnswer: v.string(),
    language: v.string(),
    frequency: v.number(), // how many times this was asked
    sourceQuestionIds: v.optional(v.array(v.string())), // links to unanswered_questions
    status: v.string(), // 'pending' | 'approved' | 'rejected'
    approvedAt: v.optional(v.number()),
    approvedBy: v.optional(v.string()),
    rejectedAt: v.optional(v.number()),
    createdAt: v.number(),
  })
    .index("by_organizationId", ["organizationId"])
    .index("by_organizationId_status", ["organizationId", "status"])
    .index("by_status", ["status"]),

  sector_common_questions: defineTable({
    sector: v.string(),
    questionPattern: v.string(), // anonymized question pattern
    frequency: v.number(),
    firstSeenAt: v.number(),
    lastSeenAt: v.number(),
    language: v.string(),
  })
    .index("by_sector", ["sector"])
    .index("by_sector_frequency", ["sector", "frequency"]),

  /**
   * Sector-specific WhatsApp conversation workflows.
   *
   * A workflow extends the AI's behaviour for specific triggers (e.g. a
   * clinic intake form, a restaurant reservation flow). Sector defaults are
   * auto-seeded during org provisioning and can be edited from the dashboard.
   */
  whatsapp_workflows: defineTable({
    organizationId: v.string(),
    name: v.string(), // "Appointment Booking", "Reservation Intake"
    description: v.optional(v.string()),
    sector: v.optional(v.string()), // sector this workflow belongs to (null for org-custom)
    triggerKeywords: v.array(v.string()), // e.g. ["book", "appointment", "حجز", "موعد"]
    triggerIntent: v.optional(v.string()), // optional AI intent match (e.g. "booking_request")
    systemPromptAddition: v.string(), // extra instructions injected when triggered
    collectFields: v.array(
      v.object({
        key: v.string(),
        labelEn: v.string(),
        labelAr: v.string(),
        type: v.string(), // 'text' | 'number' | 'date' | 'time' | 'select' | 'phone' | 'email'
        required: v.boolean(),
        options: v.optional(v.array(v.string())), // for select type
      }),
    ),
    confirmationMessageEn: v.optional(v.string()),
    confirmationMessageAr: v.optional(v.string()),
    isActive: v.boolean(),
    priority: v.number(), // higher = evaluated first
    language: v.string(), // 'en' | 'ar' | 'both'
    createdAt: v.number(),
    updatedAt: v.number(),
  })
    .index("by_organizationId", ["organizationId"])
    .index("by_organizationId_isActive", ["organizationId", "isActive"])
    .index("by_sector", ["sector"]),
};
