/**
 * Sales Collateral Model
 * Centralized sales asset library for storing, organizing, categorizing,
 * and managing all sales-related materials.
 */

import mongoose, { Schema, Document } from 'mongoose';

// ============================================
// TYPE DEFINITIONS
// ============================================

export type CollateralType =
  | 'one-pager'
  | 'brochure'
  | 'company-profile'
  | 'media-kit'
  | 'case-study'
  | 'whitepaper'
  | 'datasheet'
  | 'proposal'
  | 'product-deck'
  | 'service-deck'
  | 'pricing-sheet'
  | 'pitch-deck'
  | 'demo-video'
  | 'product-demo'
  | 'feature-document'
  | 'technical-specification'
  | 'testimonial-asset'
  | 'roi-document'
  | 'comparison-sheet'
  | 'sales-flyer'
  | 'portfolio'
  | 'client-presentation'
  | 'explainer-video';

export type CollateralStatus = 'draft' | 'approved' | 'archived';

export type CollateralCategory =
  | 'sales-presentation'
  | 'technical-document'
  | 'marketing-material'
  | 'client-proposal'
  | 'pricing'
  | 'product-education'
  | 'demo-material';

export type SalesStage =
  | 'awareness'
  | 'discovery'
  | 'qualification'
  | 'demo'
  | 'proposal'
  | 'negotiation'
  | 'closing'
  | 'retention';

export type CollateralAccessLevel =
  | 'public'
  | 'team'
  | 'department'
  | 'manager-only'
  | 'product-specific';

export interface ICollateralSection extends Document {
  id: string;
  title: string;
  content: string;
  order: number;
}

export interface IObjectionResponse extends Document {
  id: string;
  objection: string;
  response: string;
  order: number;
}

export interface ISalesCollateral extends Document {
  companyId: string;
  name: string;
  description?: string;
  type: CollateralType;
  category?: CollateralCategory;
  subcategory?: string;
  tags?: string[];
  industryTags?: string[];

  // Sales stage & department
  funnelStage?: SalesStage;
  department?: string;

  // Content fields
  valueProposition?: string;
  keyMessages?: string[];
  callToAction?: string;
  secondaryCTA?: string;
  targetPersona?: string;
  designBrief?: string;
  talkingPoints?: string[];
  sections?: ICollateralSection[];
  objectionResponses?: IObjectionResponse[];
  suggestedDistributionChannels?: string[];
  bestPractices?: string[];
  effectivenessTips?: string[];
  successMetrics?: string[];
  usageNotes?: string;
  followUpStrategy?: string;
  idealTiming?: string;

  // File & URL storage
  fileUrl?: string;
  fileType?: string;
  fileSize?: number;
  fileName?: string;
  thumbnailUrl?: string;
  externalLinks?: {
    driveUrl?: string;
    youtubeUrl?: string;
    figmaUrl?: string;
    canvaUrl?: string;
    dropboxUrl?: string;
    websiteUrl?: string;
    repoUrl?: string;
  };

  // Product/service linking
  productIds?: string[];
  serviceIds?: string[];
  packageIds?: string[];
  planIds?: string[];
  featureIds?: string[];
  icpIds: string[];

  // Version & status
  version?: string;
  status: CollateralStatus;
  accessLevel: CollateralAccessLevel;

  // Favorites & tracking
  isFavorite: boolean;
  isPinned: boolean;
  downloadCount?: number;
  usageCount?: number;

  // Linked content
  linkedData?: {
    personaIds?: string[];
    salesScriptIds?: string[];
    faqIds?: string[];
    testimonialIds?: string[];
    blogPostIds?: string[];
  };

  // Approval
  approvedBy?: string;
  approvedAt?: Date;

  // AI generation
  aiGenerated?: boolean;
  aiGenerationContext?: {
    pipelineVersion?: string;
    provider?: string;
    model?: string;
    confidence?: number;
    generatedAt?: Date;
  };

  // Legacy
  productId?: string;

  createdAt: Date;
  updatedAt: Date;
}

// ============================================
// SUB-SCHEMAS
// ============================================

const CollateralSectionSchema = new Schema<ICollateralSection>(
  {
    id: { type: String, required: true },
    title: { type: String, required: true },
    content: { type: String, default: '' },
    order: { type: Number, default: 0 },
  },
  { _id: false }
);

const ObjectionResponseSchema = new Schema<IObjectionResponse>(
  {
    id: { type: String, required: true },
    objection: { type: String, required: true },
    response: { type: String, required: true },
    order: { type: Number, default: 0 },
  },
  { _id: false }
);

// ============================================
// MAIN SCHEMA
// ============================================

const SalesCollateralSchema = new Schema<ISalesCollateral>(
  {
    companyId: {
      type: String,
      required: [true, 'Company ID is required'],
      index: true,
    },
    name: {
      type: String,
      required: [true, 'Name is required'],
      trim: true,
    },
    description: { type: String, trim: true },
    type: {
      type: String,
      required: [true, 'Type is required'],
      enum: [
        'one-pager', 'brochure', 'company-profile', 'media-kit', 'case-study',
        'whitepaper', 'datasheet', 'proposal', 'product-deck', 'service-deck',
        'pricing-sheet', 'pitch-deck', 'demo-video', 'product-demo',
        'feature-document', 'technical-specification', 'testimonial-asset',
        'roi-document', 'comparison-sheet', 'sales-flyer', 'portfolio',
        'client-presentation', 'explainer-video',
      ],
      default: 'one-pager',
    },
    category: {
      type: String,
      enum: [
        'sales-presentation', 'technical-document', 'marketing-material',
        'client-proposal', 'pricing', 'product-education', 'demo-material',
      ],
    },
    subcategory: { type: String, trim: true },
    tags: { type: [String], default: [] },
    industryTags: { type: [String], default: [] },

    // Sales stage & department
    funnelStage: {
      type: String,
      enum: ['awareness', 'discovery', 'qualification', 'demo', 'proposal', 'negotiation', 'closing', 'retention'],
    },
    department: { type: String, trim: true },

    // Content fields
    valueProposition: { type: String, trim: true },
    keyMessages: { type: [String], default: [] },
    callToAction: { type: String, trim: true },
    secondaryCTA: { type: String, trim: true },
    targetPersona: { type: String, trim: true },
    designBrief: { type: String, trim: true },
    talkingPoints: { type: [String], default: [] },
    sections: { type: [CollateralSectionSchema], default: [] },
    objectionResponses: { type: [ObjectionResponseSchema], default: [] },
    suggestedDistributionChannels: { type: [String], default: [] },
    bestPractices: { type: [String], default: [] },
    effectivenessTips: { type: [String], default: [] },
    successMetrics: { type: [String], default: [] },
    usageNotes: { type: String, trim: true },
    followUpStrategy: { type: String, trim: true },
    idealTiming: { type: String, trim: true },

    // File & URL storage
    fileUrl: { type: String, trim: true },
    fileType: { type: String, trim: true },
    fileSize: { type: Number },
    fileName: { type: String, trim: true },
    thumbnailUrl: { type: String, trim: true },
    externalLinks: {
      driveUrl: { type: String, trim: true },
      youtubeUrl: { type: String, trim: true },
      figmaUrl: { type: String, trim: true },
      canvaUrl: { type: String, trim: true },
      dropboxUrl: { type: String, trim: true },
      websiteUrl: { type: String, trim: true },
      repoUrl: { type: String, trim: true },
    },

    // Product/service linking
    productIds: { type: [String], default: [] },
    serviceIds: { type: [String], default: [] },
    packageIds: { type: [String], default: [] },
    planIds: { type: [String], default: [] },
    featureIds: { type: [String], default: [] },
    icpIds: { type: [String], default: [] },

    // Version & status
    version: { type: String, default: '1.0' },
    status: {
      type: String,
      enum: ['draft', 'approved', 'archived'],
      default: 'draft',
    },
    accessLevel: {
      type: String,
      enum: ['public', 'team', 'department', 'manager-only', 'product-specific'],
      default: 'team',
    },

    // Favorites & tracking
    isFavorite: { type: Boolean, default: false },
    isPinned: { type: Boolean, default: false },
    downloadCount: { type: Number, default: 0 },
    usageCount: { type: Number, default: 0 },

    // Linked content
    linkedData: {
      personaIds: { type: [String], default: [] },
      salesScriptIds: { type: [String], default: [] },
      faqIds: { type: [String], default: [] },
      testimonialIds: { type: [String], default: [] },
      blogPostIds: { type: [String], default: [] },
    },

    // Approval
    approvedBy: { type: String },
    approvedAt: { type: Date },

    // AI generation
    aiGenerated: { type: Boolean, default: false },
    aiGenerationContext: {
      pipelineVersion: { type: String },
      provider: { type: String },
      model: { type: String },
      confidence: { type: Number },
      generatedAt: { type: Date },
    },

    // Legacy
    productId: { type: String },
  },
  { timestamps: true }
);

// Indexes
SalesCollateralSchema.index({ companyId: 1, status: 1 });
SalesCollateralSchema.index({ companyId: 1, type: 1 });
SalesCollateralSchema.index({ companyId: 1, funnelStage: 1 });
SalesCollateralSchema.index({ companyId: 1, category: 1 });
SalesCollateralSchema.index({ companyId: 1, aiGenerated: 1 });

export const SalesCollateral = mongoose.models.SalesCollateral || mongoose.model<ISalesCollateral>('SalesCollateral', SalesCollateralSchema);