/**
 * Blog Generation Model
 *
 * Blog Generation Wizard with 12-phase workflow for guided blog creation.
 * Supports Save & Resume functionality and AI-powered content generation.
 */

import mongoose, { Schema, Document } from 'mongoose';

// ============================================
// TYPES
// ============================================

export type BlogGenerationPhase =
  | 'strategy-setup'
  | 'framework'
  | 'content-style'
  | 'seo-planning'
  | 'title-generation'
  | 'outline-generation'
  | 'structure-builder'
  | 'visual-planning'
  | 'content-generation'
  | 'seo-optimization'
  | 'multi-format'
  | 'publishing';

export type BlogGenerationStatus = 'draft' | 'in-progress' | 'completed' | 'published' | 'archived';

export type BlogFrameworkType =
  | 'pillar-cluster'
  | 'skyscraper'
  | 'listicle'
  | 'how-to'
  | 'case-study'
  | 'comparison'
  | 'story'
  | 'newsjacking';

export type BlogTone =
  | 'professional'
  | 'conversational'
  | 'casual'
  | 'technical'
  | 'storytelling'
  | 'authoritative'
  | 'empathetic';

export type BlogReadingLevel = 'beginner' | 'intermediate' | 'advanced' | 'expert';

export type BlogCTAFrequency = 'none' | 'once' | 'moderate' | 'frequent';

export type ExportFormatType = 'html' | 'wordpress' | 'markdown' | 'pdf' | 'newsletter' | 'linkedin' | 'social' | 'email';

// Phase 1: Strategy Setup
interface IStrategySetup {
  goal: string;
  contentType: string;
  primaryAudience: string;
  targetRegion: string;
  language: string;
  funnelStage: string;
  linkedData: {
    brandId?: string;
    businessProfileId?: string;
    founderIds?: string[];
    icpIds?: string[];
    personaIds?: string[];
    productIds?: string[];
    productCategoryIds?: string[];
    competitorIds?: string[];
  };
}

// Phase 2: Framework
interface IFramework {
  framework: BlogFrameworkType;
  customFramework?: string;
  frameworkReasoning?: string;
}

// Phase 3: Content Style
interface IContentStyle {
  tone: BlogTone;
  readingLevel: BlogReadingLevel;
  targetLength: number;
  ctaFrequency: BlogCTAFrequency;
  ctaType?: string;
  personalPronouns: boolean;
  includeStatistics: boolean;
  includeQuotes: boolean;
}

// Phase 4: SEO Planning
interface ISEOPlanning {
  primaryKeywords: string[];
  secondaryKeywords: string[];
  longTailKeywords: string[];
  negativeKeywords: string[];
  searchIntent: string;
  competitorUrls: string[];
  targetSERPFeatures: string[];
}

// Phase 5: Title Generation
interface IBlogGeneratedTitle {
  id: string;
  title: string;
  seoScore: number;
  clickabilityScore: number;
  suggestedKeywords: string[];
  reasoning: string;
}

interface ITitleGeneration {
  titles: IBlogGeneratedTitle[];
  selectedTitleId?: string;
  customTitle?: string;
  finalTitle: string;
  finalSlug: string;
}

// Phase 6: Outline Generation
interface IBlogOutlineSubsection {
  id: string;
  title: string;
  order: number;
  wordCountTarget: number;
}

interface IBlogOutlineSection {
  id: string;
  title: string;
  order: number;
  wordCountTarget: number;
  subsections: IBlogOutlineSubsection[];
  keyPoints: string[];
}

interface IOutlineGeneration {
  outline: IBlogOutlineSection[];
  customOutline: boolean;
  aiGenerated: boolean;
}

// Phase 7: Structure Builder
interface IStructureSection {
  id: string;
  title: string;
  order: number;
  type: 'introduction' | 'main' | 'conclusion' | 'faq' | 'toc';
  enabled: boolean;
  wordCountTarget: number;
}

interface IStructureBuilder {
  hasIntroduction: boolean;
  introductionStyle: 'story' | 'statistic' | 'question' | 'quote' | 'problem' | 'news';
  hasTOC: boolean;
  sections: IStructureSection[];
  hasFAQ: boolean;
  faqQuestions: string[];
  hasConclusion: boolean;
  conclusionStyle: 'summary' | 'cta' | 'question' | 'resource' | 'next-steps';
}

// Phase 8: Visual Planning
interface IVisualAssetConfig {
  id: string;
  type: 'image' | 'infographic' | 'chart' | 'diagram' | 'screenshot';
  prompt: string;
  placement: 'header' | 'inline' | 'sidebar' | 'conclusion';
  altText: string;
  aiGenerated: boolean;
}

interface ITableConfig {
  id: string;
  title: string;
  headers: string[];
  rows: string[][];
  placement: string;
}

interface IQuoteBoxConfig {
  id: string;
  quote: string;
  author: string;
  authorTitle?: string;
  style: 'pull-quote' | 'testimonial' | 'statistic';
}

interface ICodeSnippetConfig {
  id: string;
  language: string;
  code: string;
  filename?: string;
}

interface IVisualPlanning {
  featuredImage?: IVisualAssetConfig;
  infographics: IVisualAssetConfig[];
  tables: ITableConfig[];
  quoteBoxes: IQuoteBoxConfig[];
  codeSnippets: ICodeSnippetConfig[];
  customGraphics: IVisualAssetConfig[];
}

// Phase 9: Content Generation
interface IGeneratedSection {
  sectionId: string;
  content: string;
  wordCount: number;
  generatedAt: Date;
  editedManually: boolean;
}

interface IContentGeneration {
  status: 'pending' | 'generating' | 'partial' | 'completed' | 'failed';
  generatedSections: IGeneratedSection[];
  totalWordCount: number;
  readabilityScore: number;
  generationProgress: number;
}

// Phase 10: SEO Optimization
interface IInternalLinkSuggestion {
  url: string;
  anchorText: string;
  relevance: number;
}

interface ISEOOptimization {
  metaTitle: string;
  metaDescription: string;
  slug: string;
  schema: {
    type: 'Article' | 'HowTo' | 'FAQ' | 'Product' | 'Review';
    data: Record<string, unknown>;
  };
  canonicalUrl?: string;
  ogImage?: string;
  ogTitle?: string;
  ogDescription?: string;
  twitterCard?: string;
  internalLinks: IInternalLinkSuggestion[];
}

// Phase 11: Multi-Format
interface IExportFormatConfig {
  format: ExportFormatType;
  enabled: boolean;
  options: Record<string, unknown>;
}

interface IGeneratedOutput {
  format: ExportFormatType;
  content: string;
  generatedAt: Date;
  wordCount: number;
}

interface IMultiFormat {
  formats: IExportFormatConfig[];
  generatedOutputs: Partial<Record<ExportFormatType, IGeneratedOutput>>;
}

// Phase 12: Publishing
interface IPublishing {
  status: BlogGenerationStatus;
  publishedAt?: Date;
  scheduledAt?: Date;
  publishedTo: string[];
  performanceMetrics?: {
    views: number;
    uniqueVisitors: number;
    avgTimeOnPage: number;
    bounceRate: number;
    socialShares: number;
    backlinks: number;
  };
}

// Main Interface
export interface IBlogGeneration extends Document {
  companyId: string;
  name: string;

  // Wizard State
  currentPhase: BlogGenerationPhase;
  completedPhases: BlogGenerationPhase[];
  status: BlogGenerationStatus;
  isDraft: boolean;

  // Phase Data
  strategySetup: IStrategySetup;
  framework: IFramework;
  contentStyle: IContentStyle;
  seoPlanning: ISEOPlanning;
  titleGeneration: ITitleGeneration;
  outlineGeneration: IOutlineGeneration;
  structureBuilder: IStructureBuilder;
  visualPlanning: IVisualPlanning;
  contentGeneration: IContentGeneration;
  seoOptimization: ISEOOptimization;
  multiFormat: IMultiFormat;
  publishing: IPublishing;

  // Link to Blog Content OS
  blogContentOSId?: string;
  calendarItemId?: string;
  titleId?: string;
  postId?: string;

  // Metadata
  createdBy: string;
  lastEditedBy: string;
  version: number;

  createdAt: Date;
  updatedAt: Date;
}

// ============================================
// SCHEMAS
// ============================================

const StrategySetupSchema = new Schema({
  goal: { type: String, default: '' },
  contentType: { type: String, default: '' },
  primaryAudience: { type: String, default: '' },
  targetRegion: { type: String, default: '' },
  language: { type: String, default: 'en' },
  funnelStage: { type: String, default: '' },
  linkedData: {
    brandId: { type: String },
    businessProfileId: { type: String },
    founderIds: [{ type: String }],
    icpIds: [{ type: String }],
    personaIds: [{ type: String }],
    productIds: [{ type: String }],
    productCategoryIds: [{ type: String }],
    competitorIds: [{ type: String }],
  },
}, { _id: false });

const FrameworkSchema = new Schema({
  framework: {
    type: String,
    enum: ['pillar-cluster', 'skyscraper', 'listicle', 'how-to', 'case-study', 'comparison', 'story', 'newsjacking'],
    default: 'pillar-cluster',
  },
  customFramework: { type: String },
  frameworkReasoning: { type: String },
}, { _id: false });

const ContentStyleSchema = new Schema({
  tone: {
    type: String,
    enum: ['professional', 'conversational', 'casual', 'technical', 'storytelling', 'authoritative', 'empathetic'],
    default: 'professional',
  },
  readingLevel: {
    type: String,
    enum: ['beginner', 'intermediate', 'advanced', 'expert'],
    default: 'intermediate',
  },
  targetLength: { type: Number, default: 1500 },
  ctaFrequency: {
    type: String,
    enum: ['none', 'once', 'moderate', 'frequent'],
    default: 'moderate',
  },
  ctaType: { type: String },
  personalPronouns: { type: Boolean, default: true },
  includeStatistics: { type: Boolean, default: true },
  includeQuotes: { type: Boolean, default: false },
}, { _id: false });

const SEOPlanningSchema = new Schema({
  primaryKeywords: [{ type: String }],
  secondaryKeywords: [{ type: String }],
  longTailKeywords: [{ type: String }],
  negativeKeywords: [{ type: String }],
  searchIntent: {
    type: String,
    enum: ['informational', 'navigational', 'transactional', 'commercial'],
  },
  competitorUrls: [{ type: String }],
  targetSERPFeatures: [{ type: String }],
}, { _id: false });

const BlogGeneratedTitleSchema = new Schema({
  id: { type: String, required: true },
  title: { type: String, required: true },
  seoScore: { type: Number, default: 0 },
  clickabilityScore: { type: Number, default: 0 },
  suggestedKeywords: [{ type: String }],
  reasoning: { type: String },
}, { _id: false });

const TitleGenerationSchema = new Schema({
  titles: [BlogGeneratedTitleSchema],
  selectedTitleId: { type: String },
  customTitle: { type: String },
  finalTitle: { type: String, default: '' },
  finalSlug: { type: String, default: '' },
}, { _id: false });

const BlogOutlineSubsectionSchema = new Schema({
  id: { type: String, required: true },
  title: { type: String, required: true },
  order: { type: Number, required: true },
  wordCountTarget: { type: Number, default: 200 },
}, { _id: false });

const BlogOutlineSectionSchema = new Schema({
  id: { type: String, required: true },
  title: { type: String, required: true },
  order: { type: Number, required: true },
  wordCountTarget: { type: Number, default: 500 },
  subsections: [BlogOutlineSubsectionSchema],
  keyPoints: [{ type: String }],
}, { _id: false });

const OutlineGenerationSchema = new Schema({
  outline: [BlogOutlineSectionSchema],
  customOutline: { type: Boolean, default: false },
  aiGenerated: { type: Boolean, default: false },
}, { _id: false });

const StructureSectionSchema = new Schema({
  id: { type: String, required: true },
  title: { type: String, required: true },
  order: { type: Number, required: true },
  type: {
    type: String,
    enum: ['introduction', 'main', 'conclusion', 'faq', 'toc'],
    default: 'main',
  },
  enabled: { type: Boolean, default: true },
  wordCountTarget: { type: Number, default: 500 },
}, { _id: false });

const StructureBuilderSchema = new Schema({
  hasIntroduction: { type: Boolean, default: true },
  introductionStyle: {
    type: String,
    enum: ['story', 'statistic', 'question', 'quote', 'problem', 'news'],
    default: 'story',
  },
  hasTOC: { type: Boolean, default: true },
  sections: [StructureSectionSchema],
  hasFAQ: { type: Boolean, default: false },
  faqQuestions: [{ type: String }],
  hasConclusion: { type: Boolean, default: true },
  conclusionStyle: {
    type: String,
    enum: ['summary', 'cta', 'question', 'resource', 'next-steps'],
    default: 'cta',
  },
}, { _id: false });

const VisualAssetSchema = new Schema({
  id: { type: String, required: true },
  type: {
    type: String,
    enum: ['image', 'infographic', 'chart', 'diagram', 'screenshot'],
    default: 'image',
  },
  prompt: { type: String },
  placement: {
    type: String,
    enum: ['header', 'inline', 'sidebar', 'conclusion'],
    default: 'inline',
  },
  altText: { type: String },
  aiGenerated: { type: Boolean, default: false },
}, { _id: false });

const TableConfigSchema = new Schema({
  id: { type: String, required: true },
  title: { type: String },
  headers: [{ type: String }],
  rows: [{ type: [String] }],
  placement: { type: String },
}, { _id: false });

const QuoteBoxSchema = new Schema({
  id: { type: String, required: true },
  quote: { type: String },
  author: { type: String },
  authorTitle: { type: String },
  style: {
    type: String,
    enum: ['pull-quote', 'testimonial', 'statistic'],
    default: 'pull-quote',
  },
}, { _id: false });

const CodeSnippetSchema = new Schema({
  id: { type: String, required: true },
  language: { type: String },
  code: { type: String },
  filename: { type: String },
}, { _id: false });

const VisualPlanningSchema = new Schema({
  featuredImage: VisualAssetSchema,
  infographics: [VisualAssetSchema],
  tables: [TableConfigSchema],
  quoteBoxes: [QuoteBoxSchema],
  codeSnippets: [CodeSnippetSchema],
  customGraphics: [VisualAssetSchema],
}, { _id: false });

const GeneratedSectionSchema = new Schema({
  sectionId: { type: String, required: true },
  content: { type: String, required: true },
  wordCount: { type: Number },
  generatedAt: { type: Date, default: Date.now },
  editedManually: { type: Boolean, default: false },
}, { _id: false });

const ContentGenerationSchema = new Schema({
  status: {
    type: String,
    enum: ['pending', 'generating', 'partial', 'completed', 'failed'],
    default: 'pending',
  },
  generatedSections: [GeneratedSectionSchema],
  totalWordCount: { type: Number, default: 0 },
  readabilityScore: { type: Number, default: 0 },
  generationProgress: { type: Number, default: 0 },
}, { _id: false });

const InternalLinkSchema = new Schema({
  url: { type: String },
  anchorText: { type: String },
  relevance: { type: Number },
}, { _id: false });

const SEOOptimizationSchema = new Schema({
  metaTitle: { type: String },
  metaDescription: { type: String },
  slug: { type: String },
  schema: {
    type: { type: String, default: 'Article' },
    data: { type: Schema.Types.Mixed },
  },
  canonicalUrl: { type: String },
  ogImage: { type: String },
  ogTitle: { type: String },
  ogDescription: { type: String },
  twitterCard: { type: String },
  internalLinks: [InternalLinkSchema],
}, { _id: false });

const ExportFormatConfigSchema = new Schema({
  format: { type: String, required: true },
  enabled: { type: Boolean, default: true },
  options: { type: Schema.Types.Mixed },
}, { _id: false });

const GeneratedOutputSchema = new Schema({
  format: { type: String, required: true },
  content: { type: String, required: true },
  generatedAt: { type: Date, default: Date.now },
  wordCount: { type: Number },
}, { _id: false });

const MultiFormatSchema = new Schema({
  formats: [ExportFormatConfigSchema],
  generatedOutputs: { type: Schema.Types.Mixed },
}, { _id: false });

const PublishingSchema = new Schema({
  status: {
    type: String,
    enum: ['draft', 'in-progress', 'completed', 'published', 'archived'],
    default: 'draft',
  },
  publishedAt: { type: Date },
  scheduledAt: { type: Date },
  publishedTo: [{ type: String }],
  performanceMetrics: {
    views: { type: Number, default: 0 },
    uniqueVisitors: { type: Number, default: 0 },
    avgTimeOnPage: { type: Number, default: 0 },
    bounceRate: { type: Number, default: 0 },
    socialShares: { type: Number, default: 0 },
    backlinks: { type: Number, default: 0 },
  },
}, { _id: false });

// ============================================
// MAIN SCHEMA
// ============================================

const BlogGenerationSchema = new Schema<IBlogGeneration>(
  {
    companyId: {
      type: String,
      required: [true, 'Company ID is required'],
      index: true,
    },
    name: {
      type: String,
      required: [true, 'Blog generation name is required'],
      trim: true,
    },

    // Wizard State
    currentPhase: {
      type: String,
      enum: [
        'strategy-setup',
        'framework',
        'content-style',
        'seo-planning',
        'title-generation',
        'outline-generation',
        'structure-builder',
        'visual-planning',
        'content-generation',
        'seo-optimization',
        'multi-format',
        'publishing',
      ],
      default: 'strategy-setup',
    },
    completedPhases: {
      type: [String],
      default: [],
    },
    status: {
      type: String,
      enum: ['draft', 'in-progress', 'completed', 'published', 'archived'],
      default: 'draft',
    },
    isDraft: {
      type: Boolean,
      default: true,
    },

    // Phase Data - Using Mixed type to avoid subdocument initialization issues
    strategySetup: { type: Schema.Types.Mixed, default: {} },
    framework: { type: Schema.Types.Mixed, default: {} },
    contentStyle: { type: Schema.Types.Mixed, default: {} },
    seoPlanning: { type: Schema.Types.Mixed, default: {} },
    titleGeneration: { type: Schema.Types.Mixed, default: {} },
    outlineGeneration: { type: Schema.Types.Mixed, default: {} },
    structureBuilder: { type: Schema.Types.Mixed, default: {} },
    visualPlanning: { type: Schema.Types.Mixed, default: {} },
    contentGeneration: { type: Schema.Types.Mixed, default: {} },
    seoOptimization: { type: Schema.Types.Mixed, default: {} },
    multiFormat: { type: Schema.Types.Mixed, default: {} },
    publishing: { type: Schema.Types.Mixed, default: {} },

    // Links
    blogContentOSId: { type: String },
    calendarItemId: { type: String },
    titleId: { type: String },
    postId: { type: String },

    // Metadata
    createdBy: { type: String, required: true },
    lastEditedBy: { type: String, required: true },
    version: { type: Number, default: 1 },
  },
  {
    timestamps: true,
  }
);

// ============================================
// INDEXES
// ============================================

BlogGenerationSchema.index({ companyId: 1, status: 1 });
BlogGenerationSchema.index({ companyId: 1, createdAt: -1 });
BlogGenerationSchema.index({ companyId: 1, createdBy: 1 });
BlogGenerationSchema.index({ companyId: 1, currentPhase: 1 });

// ============================================
// EXPORT
// ============================================

export const BlogGeneration = mongoose.model<IBlogGeneration>('BlogGeneration', BlogGenerationSchema);