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

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

export const leadActivityTypeValidator = v.union(
  v.literal("NOTE"),
  v.literal("CALL"),
  v.literal("EMAIL"),
  v.literal("MEETING"),
  v.literal("WHATSAPP"),
  v.literal("STATUS_CHANGE"),
  v.literal("STAGE_CHANGE"),
  v.literal("SCORE_CHANGE"),
  v.literal("AI_QUALIFICATION"),
);

export const leadScoringEventTypeValidator = v.union(
  v.literal("RULE_MATCH"),
  v.literal("AI_SCORE"),
  v.literal("MANUAL_ADJUST"),
  v.literal("DECAY"),
);

export const leadNurtureTriggerValidator = v.union(
  v.literal("ON_CAPTURE"),
  v.literal("ON_STAGE_CHANGE"),
  v.literal("ON_SCORE_THRESHOLD"),
  v.literal("MANUAL"),
);

export const leadNurtureChannelValidator = v.union(
  v.literal("EMAIL"),
  v.literal("WHATSAPP"),
  v.literal("SMS"),
  v.literal("WAIT"),
  v.literal("CONDITION"),
);

export const leadNurtureMembershipStatusValidator = v.union(
  v.literal("ACTIVE"),
  v.literal("PAUSED"),
  v.literal("COMPLETED"),
  v.literal("EXITED"),
);

export const leadCaptureFormTypeValidator = v.union(
  v.literal("EMBED"),
  v.literal("POPUP"),
  v.literal("LANDING"),
  v.literal("WHATSAPP"),
);

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

export const leadTables = {
  leads: defineTable({
    prismaId: v.optional(v.string()),
    userId: v.string(),
    organizationId: v.optional(v.string()),
    name: v.string(),
    phone: v.optional(v.string()),
    email: v.optional(v.string()),
    company: v.optional(v.string()),
    source: v.string(),
    campaignId: v.optional(v.string()),
    interest: v.optional(v.string()),
    notes: v.optional(v.string()),
    customFields: v.any(),
    metadata: v.any(),
    status: v.string(),
    score: v.number(),
    convertedAt: v.optional(v.number()),
    lastContactAt: v.optional(v.number()),
    createdAt: v.number(),
    updatedAt: v.number(),
    assignedTo: v.optional(v.string()),
    pipelineStageId: v.optional(v.string()),
    dealValue: v.optional(v.number()),
    dealCurrency: v.optional(v.string()),
    expectedCloseAt: v.optional(v.number()),
    lostReason: v.optional(v.string()),
    qualifiedAt: v.optional(v.number()),
    qualificationScore: v.optional(v.number()),
    tags: v.array(v.string()),
    language: v.optional(v.string()),
    captureFormId: v.optional(v.string()),
    sourceChannel: v.optional(v.string()),
    firstTouchAt: v.optional(v.number()),
    lastActivityAt: v.optional(v.number()),
    touchCount: v.number(),
  })
    .index("by_email", ["email"])
    .index("by_phone", ["phone"])
    .index("by_userId_createdAt", ["userId", "createdAt"])
    .index("by_userId", ["userId"])
    .index("by_userId_source", ["userId", "source"])
    .index("by_userId_status", ["userId", "status"])
    .index("by_organizationId", ["organizationId"])
    .index("by_pipelineStageId", ["pipelineStageId"])
    .index("by_assignedTo", ["assignedTo"])
    .index("by_qualificationScore", ["qualificationScore"])
    .index("by_lastActivityAt", ["lastActivityAt"])
    .index("by_captureFormId", ["captureFormId"]),

  lead_activities: defineTable({
    prismaId: v.optional(v.string()),
    leadId: v.string(),
    userId: v.string(),
    type: leadActivityTypeValidator,
    title: v.string(),
    description: v.optional(v.string()),
    metadata: v.optional(v.any()),
    createdAt: v.number(),
  })
    .index("by_leadId", ["leadId"])
    .index("by_leadId_createdAt", ["leadId", "createdAt"])
    .index("by_userId", ["userId"])
    .index("by_type", ["type"]),

  lead_scoring_rules: defineTable({
    prismaId: v.optional(v.string()),
    userId: v.string(),
    name: v.string(),
    category: v.string(),
    condition: v.any(),
    points: v.number(),
    isActive: v.boolean(),
    createdAt: v.number(),
    updatedAt: v.number(),
  })
    .index("by_userId", ["userId"])
    .index("by_userId_isActive", ["userId", "isActive"])
    .index("by_category", ["category"]),

  lead_scoring_events: defineTable({
    prismaId: v.optional(v.string()),
    leadId: v.string(),
    eventType: leadScoringEventTypeValidator,
    ruleName: v.optional(v.string()),
    points: v.number(),
    scoreBefore: v.number(),
    scoreAfter: v.number(),
    metadata: v.optional(v.any()),
    createdAt: v.number(),
  })
    .index("by_leadId", ["leadId"])
    .index("by_leadId_createdAt", ["leadId", "createdAt"])
    .index("by_eventType", ["eventType"]),

  lead_pipeline_stages: defineTable({
    prismaId: v.optional(v.string()),
    userId: v.string(),
    name: v.string(),
    nameAr: v.optional(v.string()),
    color: v.string(),
    sortOrder: v.number(),
    isDefault: v.boolean(),
    isWon: v.boolean(),
    isLost: v.boolean(),
    createdAt: v.number(),
    updatedAt: v.number(),
  })
    .index("by_userId", ["userId"])
    .index("by_userId_sortOrder", ["userId", "sortOrder"]),

  lead_capture_forms: defineTable({
    prismaId: v.optional(v.string()),
    userId: v.string(),
    name: v.string(),
    formType: leadCaptureFormTypeValidator,
    fields: v.any(),
    styling: v.optional(v.any()),
    embedCode: v.optional(v.string()),
    isActive: v.boolean(),
    submissions: v.number(),
    createdAt: v.number(),
    updatedAt: v.number(),
  })
    .index("by_userId", ["userId"])
    .index("by_userId_isActive", ["userId", "isActive"]),

  lead_nurture_sequences: defineTable({
    prismaId: v.optional(v.string()),
    userId: v.string(),
    name: v.string(),
    description: v.optional(v.string()),
    triggerType: leadNurtureTriggerValidator,
    triggerConditions: v.optional(v.any()),
    isActive: v.boolean(),
    enrolledCount: v.number(),
    completedCount: v.number(),
    createdAt: v.number(),
    updatedAt: v.number(),
  })
    .index("by_userId", ["userId"])
    .index("by_userId_isActive", ["userId", "isActive"]),

  lead_nurture_steps: defineTable({
    prismaId: v.optional(v.string()),
    sequenceId: v.string(),
    stepOrder: v.number(),
    channel: leadNurtureChannelValidator,
    delayHours: v.number(),
    subject: v.optional(v.string()),
    content: v.optional(v.string()),
    config: v.optional(v.any()),
    createdAt: v.number(),
    updatedAt: v.number(),
  })
    .index("by_sequenceId", ["sequenceId"])
    .index("by_sequenceId_stepOrder", ["sequenceId", "stepOrder"]),

  lead_nurture_memberships: defineTable({
    prismaId: v.optional(v.string()),
    leadId: v.string(),
    sequenceId: v.string(),
    currentStep: v.number(),
    status: leadNurtureMembershipStatusValidator,
    nextActionAt: v.optional(v.number()),
    completedAt: v.optional(v.number()),
    exitedAt: v.optional(v.number()),
    exitReason: v.optional(v.string()),
    createdAt: v.number(),
    updatedAt: v.number(),
  })
    .index("by_leadId", ["leadId"])
    .index("by_sequenceId", ["sequenceId"])
    .index("by_status_nextActionAt", ["status", "nextActionAt"])
    .index("by_nextActionAt", ["nextActionAt"]),
};
