/**
 * WhatsAppCampaign Model
 * Lead nurturing automation via WhatsApp sequences with AI-powered message generation
 */

import mongoose, { Document, Schema } from 'mongoose';

// ============================================
// TYPES
// ============================================

export type WhatsAppCampaignStatus = 'draft' | 'planning' | 'generating' | 'ready' | 'active' | 'paused' | 'completed' | 'archived';
export type WhatsAppCampaignGoal =
  | 'lead-nurturing'
  | 'lead-qualification'
  | 'appointment-booking'
  | 'product-sales'
  | 'webinar-registration'
  | 'course-enrollment'
  | 'community-building'
  | 'customer-onboarding'
  | 'upsell-campaign'
  | 'retention-campaign';

export type NurturingFramework = 'educational' | 'problem-solution' | 'storytelling' | 'founder-authority' | 'product-demonstration' | 'case-study';
export type MessageTone = 'professional' | 'friendly' | 'conversational' | 'educational' | 'motivational' | 'persuasive' | 'luxury' | 'corporate';
export type PersonalizationLevel = 'basic' | 'medium' | 'advanced';
export type MessageLength = 'short' | 'medium' | 'long';
export type DataSourceKey = 'business-profile' | 'founder' | 'product' | 'icp' | 'persona' | 'competitor' | 'brand' | 'visual-identity' | 'testimonial' | 'case-study' | 'faq' | 'blog' | 'landing-page' | 'website' | 'book' | 'courses' | 'events';
export type ContentBlockType = 'founder-story' | 'customer-success' | 'testimonial' | 'case-study' | 'product-feature' | 'faq' | 'offer' | 'event-invitation' | 'webinar-promotion' | 'downloadable-resource' | 'statistic' | 'urgency';
export type TriggerEvent = 'new-lead' | 'form-submitted' | 'landing-page-signup' | 'webinar-registration' | 'product-inquiry' | 'consultation-request' | 'course-enrollment';
export type ExitCondition = 'lead-converted' | 'meeting-booked' | 'customer-purchased' | 'sequence-completed' | 'opted-out';
export type WhatsAppMessageStatus = 'pending' | 'sent' | 'delivered' | 'read' | 'replied' | 'failed';
export type MessageFrequency = 'daily' | 'alternate-day' | 'every-3-days' | 'weekly';

export interface IWhatsAppContentBlock {
  id: string;
  type: ContentBlockType;
  content: string;
  sourceId?: string;
  enabled: boolean;
}

export interface IWhatsAppNurturingMessage {
  id: string;
  day: number;
  /**
   * Calendar date this message is scheduled to send, as YYYY-MM-DD.
   * Optional: campaigns created before the date-range change carry only the
   * `day` offset, and every existing view still reads that.
   */
  scheduledDate?: string;
  timeSlot: string;
  goal: string;
  copy: string;
  cta: string;
  ctaUrl?: string;
  personalizationVariables: string[];
  media?: {
    type: 'none' | 'image' | 'video' | 'document' | 'audio';
    url?: string;
    caption?: string;
  };
  contentBlocks: IWhatsAppContentBlock[];
  status: WhatsAppMessageStatus;
  sentAt?: Date;
  deliveredAt?: Date;
  readAt?: Date;
  repliedAt?: Date;
  openRate?: number;
  responseRate?: number;
}

export interface IWhatsAppSequencePlan {
  day: number;
  /** Send date for this plan entry, YYYY-MM-DD. Optional — see the message note. */
  scheduledDate?: string;
  theme: string;
  objective: string;
  messageAngle: string;
  contentApproach: string;
}

export interface IWhatsAppAutomationConfig {
  triggerEvent: TriggerEvent;
  exitConditions: ExitCondition[];
  workingDaysOnly: boolean;
  deliveryStartTime: string;
  deliveryEndTime: string;
  timezone: string;
  optOutKeyword: string;
  maxMessagesPerDay: number;
}

export interface IWhatsAppOptimizationResult {
  openRateScore: number;
  responseRateScore: number;
  engagementScore: number;
  conversionScore: number;
  suggestions: string[];
  optimizedCopy?: string;
}

export interface IWhatsAppMultiChannelAsset {
  id: string;
  channel: 'email' | 'landing-page' | 'social-post' | 'ad-copy';
  subject?: string;
  headline?: string;
  copy: string;
  cta: string;
  status: 'draft' | 'generated';
}

export interface IWhatsAppCampaignAnalytics {
  totalSent: number;
  totalDelivered: number;
  totalRead: number;
  totalReplied: number;
  totalOptedOut: number;
  openRate: number;
  responseRate: number;
  conversionRate: number;
}

export interface IWhatsAppCampaign extends Document {
  companyId: string;
  name: string;
  description?: string;
  goals: WhatsAppCampaignGoal[];
  targetIcpIds: string[];
  targetPersonaIds: string[];
  targetRegion?: string;

  dataSources: DataSourceKey[];
  frameworks: NurturingFramework[];

  sequenceDuration: number;
  /**
   * Explicit sequence window. Together with `messageFrequency` these decide how
   * many messages are generated and on which dates. `sequenceDuration` is kept
   * (and derived from the window) so the existing list/detail views, the CSV
   * export and the public API contract continue to work unchanged.
   */
  startDate?: Date;
  endDate?: Date;
  messageFrequency: MessageFrequency;
  deliveryTime: string;
  messageLength: MessageLength;

  tone: MessageTone;
  personalizationLevel: PersonalizationLevel;
  language: string;

  sequencePlan: IWhatsAppSequencePlan[];
  planApproved: boolean;

  messages: IWhatsAppNurturingMessage[];

  optimization?: IWhatsAppOptimizationResult;

  multiChannelAssets: IWhatsAppMultiChannelAsset[];

  automation: IWhatsAppAutomationConfig;

  analytics?: IWhatsAppCampaignAnalytics;

  // Linked data from various business modules - supports both single-select (string) and multi-select (string[])
  // Key format: single-select uses 'Id' suffix (e.g., 'business-profileId', 'founderId')
  //            multi-select uses 'Ids' suffix (e.g., 'productIds', 'icpIds')
  linkedData?: Record<string, string[] | string | undefined>;

  aiGenerated?: boolean;
  aiJobId?: string;
  aiModel?: string;
  aiTokensUsed?: number;
  aiGeneratedAt?: Date;

  status: WhatsAppCampaignStatus;
  version: number;

  createdAt: Date;
  updatedAt: Date;
}

// ============================================
// SUB-SCHEMAS
// ============================================

const ContentBlockSchema = new Schema({
  id: { type: String, required: true },
  type: { type: String, required: true },
  content: { type: String, required: true },
  sourceId: { type: String },
  enabled: { type: Boolean, default: true },
}, { _id: false });

const MediaSchema = new Schema({
  type: {
    type: String,
    enum: ['none', 'image', 'video', 'document', 'audio'],
    default: 'none',
  },
  url: { type: String },
  caption: { type: String },
}, { _id: false });

const NurturingMessageSchema = new Schema({
  id: { type: String, required: true },
  day: { type: Number, required: true },
  scheduledDate: { type: String },
  timeSlot: { type: String, default: '09:00' },
  goal: { type: String, required: true },
  copy: { type: String, required: true },
  cta: { type: String, required: true },
  ctaUrl: { type: String },
  personalizationVariables: [{ type: String }],
  media: { type: MediaSchema },
  contentBlocks: [ContentBlockSchema],
  status: {
    type: String,
    enum: ['pending', 'sent', 'delivered', 'read', 'replied', 'failed'],
    default: 'pending',
  },
  sentAt: { type: Date },
  deliveredAt: { type: Date },
  readAt: { type: Date },
  repliedAt: { type: Date },
  openRate: { type: Number },
  responseRate: { type: Number },
}, { _id: false });

const SequencePlanSchema = new Schema({
  day: { type: Number, required: true },
  scheduledDate: { type: String },
  theme: { type: String, required: true },
  objective: { type: String, required: true },
  messageAngle: { type: String, required: true },
  contentApproach: { type: String, required: true },
}, { _id: false });

const AutomationConfigSchema = new Schema({
  triggerEvent: {
    type: String,
    enum: ['new-lead', 'form-submitted', 'landing-page-signup', 'webinar-registration', 'product-inquiry', 'consultation-request', 'course-enrollment'],
    default: 'new-lead',
  },
  exitConditions: [{
    type: String,
    enum: ['lead-converted', 'meeting-booked', 'customer-purchased', 'sequence-completed', 'opted-out'],
  }],
  workingDaysOnly: { type: Boolean, default: true },
  deliveryStartTime: { type: String, default: '09:00' },
  deliveryEndTime: { type: String, default: '18:00' },
  timezone: { type: String, default: 'UTC' },
  optOutKeyword: { type: String, default: 'STOP' },
  maxMessagesPerDay: { type: Number, default: 2 },
}, { _id: false });

const OptimizationResultSchema = new Schema({
  openRateScore: { type: Number, default: 0 },
  responseRateScore: { type: Number, default: 0 },
  engagementScore: { type: Number, default: 0 },
  conversionScore: { type: Number, default: 0 },
  suggestions: [{ type: String }],
  optimizedCopy: { type: String },
}, { _id: false });

const MultiChannelAssetSchema = new Schema({
  id: { type: String, required: true },
  channel: {
    type: String,
    enum: ['email', 'landing-page', 'social-post', 'ad-copy'],
    required: true,
  },
  subject: { type: String },
  headline: { type: String },
  copy: { type: String, required: true },
  cta: { type: String, required: true },
  status: {
    type: String,
    enum: ['draft', 'generated'],
    default: 'draft',
  },
}, { _id: false });

const CampaignAnalyticsSchema = new Schema({
  totalSent: { type: Number, default: 0 },
  totalDelivered: { type: Number, default: 0 },
  totalRead: { type: Number, default: 0 },
  totalReplied: { type: Number, default: 0 },
  totalOptedOut: { type: Number, default: 0 },
  openRate: { type: Number, default: 0 },
  responseRate: { type: Number, default: 0 },
  conversionRate: { type: Number, default: 0 },
}, { _id: false });

// ============================================
// MAIN SCHEMA
// ============================================

const WhatsAppCampaignSchema = new Schema<IWhatsAppCampaign>({
  companyId: { type: String, required: [true, 'Company ID is required'] },
  name: { type: String, required: [true, 'Campaign name is required'], trim: true, maxlength: [200, 'Campaign name cannot exceed 200 characters'] },
  description: { type: String, trim: true },

  // Campaign Setup
  goals: [{
    type: String,
    enum: ['lead-nurturing', 'lead-qualification', 'appointment-booking', 'product-sales', 'webinar-registration', 'course-enrollment', 'community-building', 'customer-onboarding', 'upsell-campaign', 'retention-campaign'],
  }],
  targetIcpIds: [{ type: String }],
  targetPersonaIds: [{ type: String }],
  targetRegion: { type: String },

  // Data Sources & Strategy
  dataSources: [{
    type: String,
    enum: ['business-profile', 'founder', 'product', 'icp', 'persona', 'competitor', 'brand', 'visual-identity', 'testimonial', 'case-study', 'faq', 'blog', 'landing-page', 'website', 'book', 'courses', 'events'],
  }],
  frameworks: [{
    type: String,
    enum: ['educational', 'problem-solution', 'storytelling', 'founder-authority', 'product-demonstration', 'case-study'],
  }],

  // Sequence Configuration
  sequenceDuration: { type: Number, default: 7, min: 1, max: 90 },
  // Optional so campaigns created before this change remain valid documents.
  startDate: { type: Date },
  endDate: { type: Date },
  messageFrequency: {
    type: String,
    enum: ['daily', 'alternate-day', 'every-3-days', 'weekly'],
    default: 'daily',
  },
  deliveryTime: { type: String, default: '09:00' },
  messageLength: {
    type: String,
    enum: ['short', 'medium', 'long'],
    default: 'medium',
  },

  // Content Configuration
  tone: {
    type: String,
    enum: ['professional', 'friendly', 'conversational', 'educational', 'motivational', 'persuasive', 'luxury', 'corporate'],
    default: 'friendly',
  },
  personalizationLevel: {
    type: String,
    enum: ['basic', 'medium', 'advanced'],
    default: 'medium',
  },
  language: { type: String, default: 'en' },

  // Sequence Plan
  sequencePlan: [SequencePlanSchema],
  planApproved: { type: Boolean, default: false },

  // Generated Messages
  messages: [NurturingMessageSchema],

  // AI Optimization
  optimization: { type: OptimizationResultSchema },

  // Multi-Channel Assets
  multiChannelAssets: [MultiChannelAssetSchema],

  // Automation Configuration
  automation: { type: AutomationConfigSchema, default: () => ({}) },

  // Analytics
  analytics: { type: CampaignAnalyticsSchema },

  // Linked Data - flexible structure to support various data sources
  // Single-select sources use 'Id' suffix (e.g., 'business-profileId', 'founderId', 'brandId')
  // Multi-select sources use 'Ids' suffix (e.g., 'productIds', 'icpIds', 'personaIds')
  linkedData: { type: Schema.Types.Mixed, default: () => ({}) },

  // AI Tracking
  aiGenerated: { type: Boolean, default: false },
  aiJobId: { type: String },
  aiModel: { type: String },
  aiTokensUsed: { type: Number },
  aiGeneratedAt: { type: Date },

  // Status
  status: {
    type: String,
    enum: ['draft', 'planning', 'generating', 'ready', 'active', 'paused', 'completed', 'archived'],
    default: 'draft',
  },
  version: { type: Number, default: 1 },
}, { timestamps: true });

// Indexes
WhatsAppCampaignSchema.index({ companyId: 1, status: 1 });
WhatsAppCampaignSchema.index({ companyId: 1, goals: 1 });
WhatsAppCampaignSchema.index({ companyId: 1, createdAt: -1 });

export const WhatsAppCampaign = mongoose.model<IWhatsAppCampaign>('WhatsAppCampaign', WhatsAppCampaignSchema);