/**
 * Sales Playbook Model
 * Structured playbooks for discovery, demos, negotiation, and closing
 * with objection handling, best practices, and AI generation context.
 */

import mongoose, { Schema, Document } from 'mongoose';

// ============================================
// TYPE DEFINITIONS
// ============================================

export type PlaybookType = 'discovery' | 'demo' | 'negotiation' | 'closing' | 'objection-handling' | 'onboarding' | 'retention' | 'cross-sell' | 'competitive' | 'custom';

export type PlaybookStatus = 'draft' | 'active' | 'archived';

export interface IPlaybookSection extends Document {
  id: string;
  title: string;
  content: string;
  order: number;
  type: string;
}

export interface IPlaybookObjectionResponse extends Document {
  id: string;
  objection: string;
  response: string;
  category: string;
  order: number;
}

export interface IPlaybookAiContext {
  pipelineVersion?: string;
  provider?: string;
  model?: string;
  confidence?: number;
  generatedAt?: Date;
}

export interface IPlaybookLinkedData extends Document {
  salesScriptIds?: string[];
  collateralIds?: string[];
  proposalIds?: string[];
}

export interface ISalesPlaybook extends Document {
  companyId: string;
  title: string;
  description?: string;
  type: PlaybookType;
  status: PlaybookStatus;
  targetPersona?: string;
  icpIds: string[];
  productIds: string[];
  funnelStage?: string;
  sections: IPlaybookSection[];
  objectionResponses: IPlaybookObjectionResponse[];
  bestPractices: string[];
  talkingPoints: string[];
  discoveryQuestions: string[];
  qualifyingCriteria: string[];
  competitivePositioning?: string;
  winRate?: number;
  avgDealSize?: number;
  avgCycleDays?: number;
  usageCount: number;
  aiGenerated?: boolean;
  aiGenerationContext?: IPlaybookAiContext;
  linkedData?: IPlaybookLinkedData;
  tags: string[];
  isFavorite: boolean;

  createdAt: Date;
  updatedAt: Date;
}

// ============================================
// SUB-SCHEMAS
// ============================================

const PlaybookSectionSchema = new Schema<IPlaybookSection>(
  {
    id: { type: String, required: true },
    title: { type: String, required: true },
    content: { type: String, default: '' },
    order: { type: Number, default: 0 },
    type: { type: String, trim: true },
  },
  { _id: false }
);

const PlaybookObjectionResponseSchema = new Schema<IPlaybookObjectionResponse>(
  {
    id: { type: String, required: true },
    objection: { type: String, required: true },
    response: { type: String, required: true },
    category: { type: String, trim: true },
    order: { type: Number, default: 0 },
  },
  { _id: false }
);

const PlaybookAiContextSchema = new Schema<IPlaybookAiContext>(
  {
    pipelineVersion: { type: String },
    provider: { type: String },
    model: { type: String },
    confidence: { type: Number },
    generatedAt: { type: Date },
  },
  { _id: false }
);

const PlaybookLinkedDataSchema = new Schema<IPlaybookLinkedData>(
  {
    salesScriptIds: { type: [String], default: [] },
    collateralIds: { type: [String], default: [] },
    proposalIds: { type: [String], default: [] },
  },
  { _id: false }
);

// ============================================
// MAIN SCHEMA
// ============================================

const SalesPlaybookSchema = new Schema<ISalesPlaybook>(
  {
    companyId: {
      type: String,
      required: [true, 'Company ID is required'],
      index: true,
    },
    title: {
      type: String,
      required: [true, 'Title is required'],
      trim: true,
    },
    description: { type: String, trim: true },
    type: {
      type: String,
      enum: ['discovery', 'demo', 'negotiation', 'closing', 'objection-handling', 'onboarding', 'retention', 'cross-sell', 'competitive', 'custom'],
      default: 'discovery',
    },
    status: {
      type: String,
      enum: ['draft', 'active', 'archived'],
      default: 'draft',
    },
    targetPersona: { type: String, trim: true },
    icpIds: { type: [String], default: [] },
    productIds: { type: [String], default: [] },
    funnelStage: { type: String, trim: true },
    sections: { type: [PlaybookSectionSchema], default: [] },
    objectionResponses: { type: [PlaybookObjectionResponseSchema], default: [] },
    bestPractices: { type: [String], default: [] },
    talkingPoints: { type: [String], default: [] },
    discoveryQuestions: { type: [String], default: [] },
    qualifyingCriteria: { type: [String], default: [] },
    competitivePositioning: { type: String, trim: true },
    winRate: { type: Number },
    avgDealSize: { type: Number },
    avgCycleDays: { type: Number },
    usageCount: { type: Number, default: 0 },
    aiGenerated: { type: Boolean, default: false },
    aiGenerationContext: { type: PlaybookAiContextSchema },
    linkedData: { type: PlaybookLinkedDataSchema },
    tags: { type: [String], default: [] },
    isFavorite: { type: Boolean, default: false },
  },
  { timestamps: true }
);

// Indexes
SalesPlaybookSchema.index({ companyId: 1, status: 1 });
SalesPlaybookSchema.index({ companyId: 1, type: 1 });

export const SalesPlaybook = mongoose.models.SalesPlaybook || mongoose.model<ISalesPlaybook>('SalesPlaybook', SalesPlaybookSchema);