/**
 * Case Study Model
 * Manages case studies for social proof
 * Case Study Management Models
 *
 * CaseStudyCategory — hierarchical categories for organising case studies
 * CaseStudy — comprehensive case study / success story records
 */

import mongoose, { Schema, Document } from 'mongoose';

// ============================================
// CASE STUDY CATEGORY
// ============================================

export type CaseStudyCategoryStatus = 'draft' | 'review' | 'approved' | 'published';

export interface ICaseStudyCategory extends Document {
  companyId: string;
  name: string;
  slug: string;
  description?: string;
  parentId?: string;
  icon?: string;
  colour?: string;
  order: number;
  caseStudyCount: number;
  status: CaseStudyCategoryStatus;
  createdAt: Date;
  updatedAt: Date;
}

const CaseStudyCategorySchema = new Schema<ICaseStudyCategory>(
  {
    companyId: { type: String, required: [true, 'Company ID is required'] },
    name: { type: String, required: [true, 'Category name is required'], trim: true, maxlength: [100, 'Category name cannot exceed 100 characters'] },
    slug: { type: String, trim: true, lowercase: true },
    description: { type: String, trim: true },
    parentId: { type: String, index: true },
    icon: { type: String, trim: true },
    colour: { type: String, trim: true },
    order: { type: Number, default: 0 },
    caseStudyCount: { type: Number, default: 0 },
    status: { type: String, enum: ['draft', 'review', 'approved', 'published'], default: 'draft' },
  },
  { timestamps: true }
);

CaseStudyCategorySchema.index({ companyId: 1, parentId: 1 });
CaseStudyCategorySchema.index({ companyId: 1, slug: 1 }, { unique: true });

CaseStudyCategorySchema.pre('save', function (this: ICaseStudyCategory) {
  if (this.isModified('name') || !this.slug) {
    this.slug = this.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
  }
});

// ============================================
// CASE STUDY KPI SUB-SCHEMA
// ============================================

const CaseStudyKPISchema = new Schema(
  {
    label: { type: String, required: true },
    value: { type: String, required: true },
    beforeValue: { type: String },
    afterValue: { type: String },
    unit: { type: String },
    changePercent: { type: Number },
  },
  { _id: false }
);

// ============================================
// CASE STUDY STEP SUB-SCHEMA
// ============================================

const CaseStudyStepSchema = new Schema(
  {
    id: { type: String, required: true },
    title: { type: String, required: true, maxlength: [200, 'Step title cannot exceed 200 characters'] },
    description: { type: String, default: '' },
    order: { type: Number, required: true },
    type: { type: String, enum: ['challenge', 'strategy', 'execution', 'result', 'note'], default: 'strategy' },
    assignee: { type: String },
    estimatedTime: { type: String },
    checklist: { type: [String], default: [] },
    attachments: {
      type: [{
        url: { type: String, required: true },
        name: { type: String, required: true },
        type: { type: String, required: true },
        size: { type: Number },
      }],
      default: [],
    },
  },
  { _id: false }
);

// ============================================
// CASE STUDY VERSION SUB-SCHEMA
// ============================================

const CaseStudyVersionSchema = new Schema(
  {
    id: { type: String, required: true },
    version: { type: Number, required: true },
    changeSummary: { type: String, default: '' },
    modifiedBy: { type: String, default: '' },
    modifiedAt: { type: Date, default: Date.now },
    approvedBy: { type: String },
    approvedAt: { type: Date },
  },
  { _id: false }
);

// ============================================
// CASE STUDY MEDIA SUB-SCHEMA
// ============================================

const CaseStudyMediaSchema = new Schema(
  {
    url: { type: String, required: true },
    name: { type: String, required: true },
    type: { type: String, required: true },
    size: { type: Number },
    caption: { type: String },
    mediaType: { type: String, enum: ['image', 'video', 'document', 'chart', 'graph', 'screenshot', 'pdf', 'other'], default: 'image' },
  },
  { _id: false }
);

// ============================================
// CASE STUDY
// ============================================

export type CaseStudyStatus = 'draft' | 'review' | 'approved' | 'published' | 'archived';
export type CaseStudyPriority = 'low' | 'medium' | 'high' | 'critical';
export type CaseStudyVisibility = 'private' | 'internal' | 'public';
export type CaseStudyIndustry = 'technology' | 'healthcare' | 'finance' | 'education' | 'retail' | 'manufacturing' | 'real-estate' | 'saas' | 'ecommerce' | 'marketing' | 'consulting' | 'other';
export type CaseStudyDepartment = 'engineering' | 'marketing' | 'sales' | 'design' | 'operations' | 'hr' | 'finance' | 'customer-success' | 'product' | 'legal' | 'other';

export interface ICaseStudy extends Document {
  companyId: string;
  caseStudyId: string;

  // Core Content
  title: string;
  slug: string;
  shortDescription?: string;
  detailedDescription?: string;
  executiveSummary?: string;

  // Client Information
  clientName?: string;
  clientIndustry?: CaseStudyIndustry;
  clientWebsite?: string;
  clientLogo?: string;

  // Classification
  categoryId?: string;
  department: CaseStudyDepartment;
  industry: CaseStudyIndustry;
  tags: string[];
  servicesUsed: string[];
  productsUsed: string[];

  // Case Study Structure
  challenge?: string;
  goals?: string;
  solution?: string;
  strategy?: string;
  executionSteps?: string;
  results?: string;
  keyTakeaways: string[];

  // Before/After
  beforeDescription?: string;
  afterDescription?: string;
  beforeMetrics: string[];
  afterMetrics: string[];

  // KPIs & Metrics
  kpis: any[];

  // Steps/Workflow
  steps: any[];

  // Testimonials
  testimonials: any[];

  // Status & Workflow
  status: CaseStudyStatus;
  priority: CaseStudyPriority;
  visibility: CaseStudyVisibility;

  // Approval
  approvalStatus: 'pending' | 'approved' | 'rejected' | 'changes_requested';
  approvedBy?: string;
  approvedAt?: Date;
  reviewer?: string;
  reviewNotes?: string;

  // Authorship
  owner?: string;
  author?: string;

  // SEO
  metaTitle?: string;
  metaDescription?: string;
  seoKeywords: string[];
  ogTitle?: string;
  ogDescription?: string;
  ogImage?: string;

  // Relationships
  relatedCaseStudyIds: string[];
  relatedSopIds: string[];
  relatedCourseIds: string[];
  relatedFaqIds: string[];
  relatedProductIds: string[];

  // Media & Attachments
  mediaAttachments: any[];
  featuredImage?: string;
  heroImage?: string;

  // Versioning
  version: number;
  versionHistory: any[];
  templateId?: string;
  isTemplate: boolean;

  // AI
  aiGenerated: boolean;
  internalNotes?: string;

  // Analytics
  viewCount: number;
  shareCount: number;
  downloadCount: number;

  createdAt: Date;
  updatedAt: Date;
}

const CaseStudySchema = new Schema<ICaseStudy>(
  {
    companyId: { type: String, required: [true, 'Company ID is required'] },
    caseStudyId: { type: String, required: true, uppercase: true, match: /^CS-\d+$/ },

    // Core Content
    title: { type: String, required: [true, 'Title is required'], trim: true, maxlength: [300, 'Title cannot exceed 300 characters'] },
    slug: { type: String, trim: true, lowercase: true },
    shortDescription: { type: String, trim: true, maxlength: [500, 'Short description cannot exceed 500 characters'] },
    detailedDescription: { type: String, trim: true },
    executiveSummary: { type: String, trim: true },

    // Client Information
    clientName: { type: String, trim: true },
    clientIndustry: { type: String, enum: ['technology', 'healthcare', 'finance', 'education', 'retail', 'manufacturing', 'real-estate', 'saas', 'ecommerce', 'marketing', 'consulting', 'other'] },
    clientWebsite: { type: String, trim: true },
    clientLogo: { type: String, trim: true },

    // Classification
    categoryId: { type: String, index: true },
    department: { type: String, enum: ['engineering', 'marketing', 'sales', 'design', 'operations', 'hr', 'finance', 'customer-success', 'product', 'legal', 'other'], default: 'marketing' },
    industry: { type: String, enum: ['technology', 'healthcare', 'finance', 'education', 'retail', 'manufacturing', 'real-estate', 'saas', 'ecommerce', 'marketing', 'consulting', 'other'], default: 'technology' },
    tags: { type: [String], default: [] },
    servicesUsed: { type: [String], default: [] },
    productsUsed: { type: [String], default: [] },

    // Case Study Structure
    challenge: { type: String, trim: true },
    goals: { type: String, trim: true },
    solution: { type: String, trim: true },
    strategy: { type: String, trim: true },
    executionSteps: { type: String, trim: true },
    results: { type: String, trim: true },
    keyTakeaways: { type: [String], default: [] },

    // Before/After
    beforeDescription: { type: String, trim: true },
    afterDescription: { type: String, trim: true },
    beforeMetrics: { type: [String], default: [] },
    afterMetrics: { type: [String], default: [] },

    // KPIs & Metrics
    kpis: { type: [CaseStudyKPISchema] as any, default: [] },

    // Steps/Workflow
    steps: { type: [CaseStudyStepSchema] as any, default: [] },

    // Testimonials
    testimonials: { type: [{
      quote: { type: String, required: true },
      author: { type: String, required: true },
      role: { type: String },
      company: { type: String },
    }], default: [] },

    // Status & Workflow
    status: { type: String, enum: ['draft', 'review', 'approved', 'published', 'archived'], default: 'draft' },
    priority: { type: String, enum: ['low', 'medium', 'high', 'critical'], default: 'medium' },
    visibility: { type: String, enum: ['private', 'internal', 'public'], default: 'internal' },

    // Approval
    approvalStatus: { type: String, enum: ['pending', 'approved', 'rejected', 'changes_requested'], default: 'pending' },
    approvedBy: { type: String },
    approvedAt: { type: Date },
    reviewer: { type: String },
    reviewNotes: { type: String },

    // Authorship
    owner: { type: String },
    author: { type: String },

    // SEO
    metaTitle: { type: String, trim: true, maxlength: [60, 'Meta title cannot exceed 60 characters'] },
    metaDescription: { type: String, trim: true, maxlength: [160, 'Meta description cannot exceed 160 characters'] },
    seoKeywords: { type: [String], default: [] },
    ogTitle: { type: String, trim: true },
    ogDescription: { type: String, trim: true },
    ogImage: { type: String, trim: true },

    // Relationships
    relatedCaseStudyIds: { type: [String], default: [] },
    relatedSopIds: { type: [String], default: [] },
    relatedCourseIds: { type: [String], default: [] },
    relatedFaqIds: { type: [String], default: [] },
    relatedProductIds: { type: [String], default: [] },

    // Media & Attachments
    mediaAttachments: { type: [CaseStudyMediaSchema] as any, default: [] },
    featuredImage: { type: String, trim: true },
    heroImage: { type: String, trim: true },

    // Versioning
    version: { type: Number, default: 1 },
    versionHistory: { type: [CaseStudyVersionSchema] as any, default: [] },
    templateId: { type: String },
    isTemplate: { type: Boolean, default: false },

    // AI
    aiGenerated: { type: Boolean, default: false },
    internalNotes: { type: String },

    // Analytics
    viewCount: { type: Number, default: 0 },
    shareCount: { type: Number, default: 0 },
    downloadCount: { type: Number, default: 0 },
  },
  { timestamps: true }
);

// Compound indexes
CaseStudySchema.index({ companyId: 1, status: 1 });
CaseStudySchema.index({ companyId: 1, categoryId: 1 });
CaseStudySchema.index({ companyId: 1, caseStudyId: 1 }, { unique: true });
CaseStudySchema.index({ companyId: 1, slug: 1 }, { unique: true });
CaseStudySchema.index({ companyId: 1, department: 1 });
CaseStudySchema.index({ companyId: 1, industry: 1 });
CaseStudySchema.index({ title: 'text', shortDescription: 'text', detailedDescription: 'text', challenge: 'text', solution: 'text' });

CaseStudySchema.pre('save', function (this: ICaseStudy) {
  if (this.isModified('title') || !this.slug) {
    this.slug = this.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
  }
});

export const CaseStudyCategory = mongoose.model<ICaseStudyCategory>('CaseStudyCategory', CaseStudyCategorySchema);
export const CaseStudy = mongoose.model<ICaseStudy>('CaseStudy', CaseStudySchema);