/**
 * Presentation Model
 *
 * AI-powered presentations for company profiles, products, investor pitches, and events.
 * Supports multiple presentation types, slide management, version history, and export.
 */

import mongoose, { Schema, Document, models, Model } from 'mongoose';

// ============================================
// TYPES
// ============================================

export type PresentationType =
  | 'company-profile'
  | 'product'
  | 'investor-pitch'
  | 'event-outdoor'
  | 'sales-pitch'
  | 'marketing-campaign'
  | 'training-onboarding'
  | 'quarterly-review'
  | 'project-proposal'
  | 'partnership-proposal'
  | 'investor-update'
  | 'product-launch'
  | 'case-study';
export type PresentationTone = 'professional' | 'startup' | 'corporate' | 'sales' | 'investor';
export type PresentationStatus = 'draft' | 'in-review' | 'approved' | 'published' | 'archived';
export type PresentationSlideLayout = 'single-column' | 'two-column' | 'image-left' | 'image-right' | 'full-image';
export type PresentationTemplateStyle = 'modern' | 'corporate' | 'creative' | 'minimal' | 'storytelling';

export type PresentationSlideType =
  | 'title'
  | 'problem'
  | 'solution'
  | 'market'
  | 'product'
  | 'business-model'
  | 'traction'
  | 'team'
  | 'financials'
  | 'competition'
  | 'ask'
  | 'timeline'
  | 'custom'
  | 'about'
  | 'demo'
  | 'case-study'
  | 'pricing'
  | 'next-steps'
  | 'vision-mission'
  | 'services-products'
  | 'achievements'
  | 'client-portfolio'
  | 'contact'
  | 'benefits'
  | 'use-cases'
  | 'testimonials'
  | 'call-to-action'
  | 'objective'
  | 'brand-message'
  | 'sponsorship'
  | 'exhibition'
  | 'franchise'
  | 'partnership'
  | 'marketing-campaign';

export interface IPresentationSlide {
  id: string;
  order: number;
  type: PresentationSlideType;
  title: string;
  subtitle?: string;
  content?: string;
  notes?: string;
  mediaUrls?: string[];
  chartData?: Record<string, unknown>;
  layout?: PresentationSlideLayout;
  aiGenerated?: boolean;
  generatedAt?: Date;
  promptContext?: string;
}

export interface IPresentationVersion {
  version: number;
  slides: IPresentationSlide[];
  savedAt: Date;
  savedBy: string;
  changeLog?: string;
}

export interface IPresentationDataSource {
  businessProfileId?: string;
  visualIdentityId?: string;
  brandStrategyId?: string;
  productIds?: string[];
  icpIds?: string[];
  personaIds?: string[];
  competitorIds?: string[];
  founderIds?: string[];
  employeeIds?: string[];
  caseStudyIds?: string[];
  websitePlannerId?: string[];
  manualInput?: {
    companyName?: string;
    industry?: string;
    targetAudience?: string;
    keyMessage?: string;
    customData?: Record<string, string>;
  };
}

export interface IPresentation extends Document {
  companyId: string;
  title: string;
  type: PresentationType;
  status: PresentationStatus;

  businessName: string;
  industry: string;
  targetAudience: string;
  keyMessage: string;
  tone: PresentationTone;
  templateStyle?: PresentationTemplateStyle;
  numberOfSlides?: number;
  language?: string;

  slides: IPresentationSlide[];
  dataSource: IPresentationDataSource;

  version: number;
  previousVersions?: IPresentationVersion[];

  aiPromptConfigId?: string;
  generatedAt?: Date;

  exportSettings?: {
    format: 'pdf' | 'pptx';
    branding: boolean;
    includeNotes: boolean;
    lastExportedAt?: Date;
  };

  generatedContent?: {
    status: 'none' | 'generating' | 'completed' | 'failed';
    jobId?: string;
    generatedAt?: Date;
    updatedAt?: Date;
    error?: string;
    slides?: IPresentationSlide[];
  };

  approvalStatus?: 'pending' | 'approved' | 'rejected';
  approvedBy?: string;
  approvedAt?: Date;

  tags?: string[];
  createdBy: string;
}

// ============================================
// SCHEMAS
// ============================================

const SlideSchema = new Schema<IPresentationSlide>(
  {
    id: { type: String, required: true },
    order: { type: Number, required: true },
    type: {
      type: String,
      required: true,
      enum: [
        'title', 'problem', 'solution', 'market', 'product', 'business-model',
        'traction', 'team', 'financials', 'competition', 'ask', 'timeline',
        'custom', 'about', 'demo', 'case-study', 'pricing', 'next-steps',
        'vision-mission', 'services-products', 'achievements', 'client-portfolio',
        'contact', 'benefits', 'use-cases', 'testimonials', 'call-to-action',
        'objective', 'brand-message', 'sponsorship', 'exhibition', 'franchise',
        'partnership', 'marketing-campaign', 'content'
      ],
    },
    title: { type: String, required: true },
    subtitle: { type: String },
    content: { type: String },
    notes: { type: String },
    mediaUrls: [{ type: String }],
    chartData: { type: Schema.Types.Mixed },
    layout: {
      type: String,
      enum: ['single-column', 'two-column', 'image-left', 'image-right', 'full-image'],
      default: 'single-column',
    },
    aiGenerated: { type: Boolean, default: false },
    generatedAt: { type: Date },
    promptContext: { type: String },
  },
  { _id: false }
);

const VersionSchema = new Schema<IPresentationVersion>(
  {
    version: { type: Number, required: true },
    slides: [SlideSchema],
    savedAt: { type: Date, default: Date.now },
    savedBy: { type: String, required: true },
    changeLog: { type: String },
  },
  { _id: false }
);

const DataSourceSchema = new Schema<IPresentationDataSource>(
  {
    businessProfileId: { type: String },
    visualIdentityId: { type: String },
    brandStrategyId: { type: String },
    productIds: [{ type: String }],
    icpIds: [{ type: String }],
    personaIds: [{ type: String }],
    competitorIds: [{ type: String }],
    founderIds: [{ type: String }],
    employeeIds: [{ type: String }],
    caseStudyIds: [{ type: String }],
    websitePlannerId: [{ type: String }],
    manualInput: {
      companyName: { type: String },
      industry: { type: String },
      targetAudience: { type: String },
      keyMessage: { type: String },
      customData: { type: Schema.Types.Mixed },
    },
  },
  { _id: false }
);

const PresentationSchema = new Schema<IPresentation>(
  {
    companyId: { type: String, required: true, index: true },
    title: { type: String, required: true, maxlength: 200 },
    type: {
      type: String,
      enum: [
        'company-profile',
        'product',
        'investor-pitch',
        'event-outdoor',
        'sales-pitch',
        'marketing-campaign',
        'training-onboarding',
        'quarterly-review',
        'project-proposal',
        'partnership-proposal',
        'investor-update',
        'product-launch',
        'case-study',
      ],
      required: true,
    },
    status: {
      type: String,
      enum: ['draft', 'in-review', 'approved', 'published', 'archived'],
      default: 'draft',
    },

    businessName: { type: String, required: true },
    industry: { type: String, required: true },
    targetAudience: { type: String, required: true },
    keyMessage: { type: String, required: true },
    tone: {
      type: String,
      enum: ['professional', 'startup', 'corporate', 'sales', 'investor'],
      default: 'professional',
    },
    templateStyle: {
      type: String,
      enum: ['modern', 'corporate', 'creative', 'minimal', 'storytelling'],
      default: 'modern',
    },
    numberOfSlides: { type: Number },
    language: { type: String, default: 'en' },

    slides: [SlideSchema],
    dataSource: DataSourceSchema,

    version: { type: Number, default: 1 },
    previousVersions: [VersionSchema],

    aiPromptConfigId: { type: String },
    generatedAt: { type: Date },

    exportSettings: {
      format: { type: String, enum: ['pdf', 'pptx'], default: 'pdf' },
      branding: { type: Boolean, default: true },
      includeNotes: { type: Boolean, default: false },
      lastExportedAt: { type: Date },
    },

    generatedContent: {
      status: { type: String, enum: ['none', 'generating', 'completed', 'failed'], default: 'none' },
      jobId: { type: String },
      generatedAt: { type: Date },
      updatedAt: { type: Date },
      error: { type: String },
      slides: [SlideSchema],
    },

    approvalStatus: {
      type: String,
      enum: ['pending', 'approved', 'rejected'],
    },
    approvedBy: { type: String },
    approvedAt: { type: Date },

    tags: [{ type: String }],
    createdBy: { type: String, required: true },
  },
  { timestamps: true }
);

// ============================================
// INDEXES
// ============================================

PresentationSchema.index({ companyId: 1, status: 1 });
PresentationSchema.index({ companyId: 1, type: 1 });
PresentationSchema.index({ companyId: 1, createdAt: -1 });
PresentationSchema.index({ companyId: 1, createdBy: 1 });

// ============================================
// MODEL
// ============================================

export const Presentation: Model<IPresentation> =
  models.Presentation || mongoose.model<IPresentation>('Presentation', PresentationSchema);

export default Presentation;