/**
 * Knowledge Panel Model
 * Manages Google Knowledge Panel optimisation, claiming, schema markup, and change tracking for the PR Content Studio
 */

import mongoose, { Schema, Document } from 'mongoose';

// ============================================
// TYPE DEFINITIONS
// ============================================

export type KnowledgePanelStatus = 'not-claimed' | 'claimed' | 'verified' | 'partially-verified';
export type KnowledgeEntryStatus = 'draft' | 'generated' | 'reviewed' | 'published';
export type KnowledgeEntryCategory = 'company-info' | 'product-info' | 'service-info' | 'founder-info' | 'achievement' | 'milestone' | 'faq' | 'best-practice' | 'reference' | 'other';

export type AttributePriority = 'critical' | 'high' | 'medium' | 'low';
export type VerificationStepStatus = 'pending' | 'completed' | 'failed';
export type OptimisationPriority = 'critical' | 'high' | 'medium' | 'low';
export type OptimisationStatus = 'pending' | 'in-progress' | 'completed';
export type ChangeType = 'added' | 'removed' | 'modified';
export type KnowledgeSectionType = 'overview' | 'features' | 'benefits' | 'use-cases' | 'documentation' | 'faq' | 'best-practices' | 'notes' | 'references' | 'custom';
export type KnowledgeMediaType = 'image' | 'video' | 'document' | 'pdf' | 'embed' | 'link' | 'other';
export type AIGeneratedType = 'summary' | 'description' | 'insight' | 'faq' | 'action-item' | 'section-content';

export interface IPanelAttribute {
  key: string;
  value: string;
  priority?: AttributePriority;
}

export interface IPanelData {
  name: string;
  description: string;
  type: string;
  attributes: IPanelAttribute[];
}

export interface IVerificationStep {
  step: string;
  status: VerificationStepStatus;
  method: string;
  verifiedDate: string;
  notes: string;
}

export interface IOptimisation {
  category: string;
  suggestion: string;
  priority: OptimisationPriority;
  status: OptimisationStatus;
  impact: string;
  action: string;
}

export interface IChangeLogEntry {
  date: string;
  changeType: ChangeType;
  field: string;
  oldValue: string;
  newValue: string;
  detectedBy: string;
}

export interface ITopAction {
  action: string;
  priority: string;
  completed: boolean;
}

export interface IKnowledgeSection {
  id: string;
  sectionType: KnowledgeSectionType;
  title: string;
  content: string;
  order: number;
}

export interface IKnowledgeMedia {
  id: string;
  url: string;
  name: string;
  type: string;
  size?: number;
  caption?: string;
  mediaType: KnowledgeMediaType;
  order: number;
}

export interface IKpDocumentAttachment {
  id: string;
  url: string;
  name: string;
  type: string;
  size?: number;
  description?: string;
  version: number;
  uploadedAt: string;
}

export interface IAIGeneratedContent {
  id: string;
  generatedType: AIGeneratedType;
  content: string;
  prompt?: string;
  model?: string;
  generatedAt: string;
  applied: boolean;
}

export interface IKnowledgePanel extends Document {
  companyId: string;
  panelStatus: KnowledgePanelStatus;
  completenessScore: number;
  whatGoogleShows: IPanelData;
  whatWeWant: IPanelData;
  verificationSteps: IVerificationStep[];
  schemaMarkup: string;
  schemaType: string;
  optimisations: IOptimisation[];
  changeLog: IChangeLogEntry[];
  topActions: ITopAction[];
  wikiArticleLinked: boolean;
  wikiArticleId: string;
  tags: string[];
  version: number;
  language?: string;
  // Entry Management
  title: string;
  status: KnowledgeEntryStatus;
  category: KnowledgeEntryCategory;
  isFeatured: boolean;
  // Rich Content Sections
  sections: IKnowledgeSection[];
  // Rich Text Content
  summary: string;
  description: string;
  // Media Support
  media: IKnowledgeMedia[];
  featuredImage?: string;
  // Document & Attachment Management
  attachments: IKpDocumentAttachment[];
  // Module Linking & Relationships
  linkedProductIds: string[];
  linkedServiceIds: string[];
  linkedProjectIds: string[];
  linkedTeamIds: string[];
  linkedDocumentIds: string[];
  linkedCampaignIds: string[];
  linkedWikiArticleId: string;
  relatedKnowledgePanelIds: string[];
  // AI-Generated Content History
  aiGeneratedContent: IAIGeneratedContent[];
  // Import/Export Metadata
  importedFrom?: string;
  importedAt?: string;
  lastExportedAt?: string;
  lastExportedFormat?: string;
  createdAt: Date;
  updatedAt: Date;
}

// ============================================
// SUB-SCHEMAS
// ============================================

const PanelAttributeSchema = new Schema<IPanelAttribute>({
  key: { type: String, default: '' },
  value: { type: String, default: '' },
  priority: {
    type: String,
    enum: ['critical', 'high', 'medium', 'low'],
    default: 'medium'
  }
}, { _id: false });

const PanelDataSchema = new Schema<IPanelData>({
  name: { type: String, default: '' },
  description: { type: String, default: '' },
  type: { type: String, default: '' },
  attributes: { type: [PanelAttributeSchema], default: [] }
}, { _id: false });

const VerificationStepSchema = new Schema<IVerificationStep>({
  step: { type: String, default: '' },
  status: {
    type: String,
    enum: ['pending', 'completed', 'failed'],
    default: 'pending'
  },
  method: { type: String, default: '' },
  verifiedDate: { type: String, default: '' },
  notes: { type: String, default: '' }
}, { _id: false });

const OptimisationSchema = new Schema<IOptimisation>({
  category: { type: String, default: '' },
  suggestion: { type: String, default: '' },
  priority: {
    type: String,
    enum: ['critical', 'high', 'medium', 'low'],
    default: 'medium'
  },
  status: {
    type: String,
    enum: ['pending', 'in-progress', 'completed'],
    default: 'pending'
  },
  impact: { type: String, default: '' },
  action: { type: String, default: '' }
}, { _id: false });

const ChangeLogEntrySchema = new Schema<IChangeLogEntry>({
  date: { type: String, default: '' },
  changeType: {
    type: String,
    enum: ['added', 'removed', 'modified'],
    default: 'added'
  },
  field: { type: String, default: '' },
  oldValue: { type: String, default: '' },
  newValue: { type: String, default: '' },
  detectedBy: { type: String, default: '' }
}, { _id: false });

const TopActionSchema = new Schema<ITopAction>({
  action: { type: String, default: '' },
  priority: { type: String, default: 'medium' },
  completed: { type: Boolean, default: false }
}, { _id: false });

const KnowledgeSectionSchema = new Schema<IKnowledgeSection>({
  id: { type: String, default: '' },
  sectionType: {
    type: String,
    enum: ['overview', 'features', 'benefits', 'use-cases', 'documentation', 'faq', 'best-practices', 'notes', 'references', 'custom'],
    default: 'overview'
  },
  title: { type: String, default: '' },
  content: { type: String, default: '' },
  order: { type: Number, default: 0 }
}, { _id: false });

const KnowledgeMediaSchema = new Schema<IKnowledgeMedia>({
  id: { type: String, default: '' },
  url: { type: String, default: '' },
  name: { type: String, default: '' },
  type: { type: String, default: '' },
  size: { type: Number },
  caption: { type: String },
  mediaType: {
    type: String,
    enum: ['image', 'video', 'document', 'pdf', 'embed', 'link', 'other'],
    default: 'image'
  },
  order: { type: Number, default: 0 }
}, { _id: false });

const KpDocumentAttachmentSchema = new Schema<IKpDocumentAttachment>({
  id: { type: String, default: '' },
  url: { type: String, default: '' },
  name: { type: String, default: '' },
  type: { type: String, default: '' },
  size: { type: Number },
  description: { type: String },
  version: { type: Number, default: 1 },
  uploadedAt: { type: String, default: '' }
}, { _id: false });

const AIGeneratedContentSchema = new Schema<IAIGeneratedContent>({
  id: { type: String, default: '' },
  generatedType: {
    type: String,
    enum: ['summary', 'description', 'insight', 'faq', 'action-item', 'section-content'],
    default: 'summary'
  },
  content: { type: String, default: '' },
  prompt: { type: String },
  model: { type: String },
  generatedAt: { type: String, default: '' },
  applied: { type: Boolean, default: false }
}, { _id: false });

// ============================================
// MAIN SCHEMA
// ============================================

const KnowledgePanelSchema = new Schema<IKnowledgePanel>({
  companyId: {
    type: String,
    required: [true, 'Company ID is required'],
    index: true
  },
  panelStatus: {
    type: String,
    enum: ['not-claimed', 'claimed', 'verified', 'partially-verified'],
    default: 'not-claimed'
  },
  completenessScore: { type: Number, default: 0 },
  whatGoogleShows: { type: PanelDataSchema, default: () => ({ name: '', description: '', type: '', attributes: [] }) },
  whatWeWant: { type: PanelDataSchema, default: () => ({ name: '', description: '', type: '', attributes: [] }) },
  verificationSteps: { type: [VerificationStepSchema], default: [] },
  schemaMarkup: { type: String, default: '' },
  schemaType: { type: String, default: 'Organization' },
  optimisations: { type: [OptimisationSchema], default: [] },
  changeLog: { type: [ChangeLogEntrySchema], default: [] },
  topActions: { type: [TopActionSchema], default: [] },
  wikiArticleLinked: { type: Boolean, default: false },
  wikiArticleId: { type: String, default: '' },
  tags: [{ type: String, trim: true }],
  version: { type: Number, default: 1 },
  language: { type: String, default: 'en' },
  // Entry Management
  title: { type: String, default: '' },
  status: {
    type: String,
    enum: ['draft', 'generated', 'reviewed', 'published'],
    default: 'draft'
  },
  category: {
    type: String,
    enum: ['company-info', 'product-info', 'service-info', 'founder-info', 'achievement', 'milestone', 'faq', 'best-practice', 'reference', 'other'],
    default: 'other'
  },
  isFeatured: { type: Boolean, default: false },
  // Rich Content Sections
  sections: { type: [KnowledgeSectionSchema], default: [] },
  // Rich Text Content
  summary: { type: String, default: '' },
  description: { type: String, default: '' },
  // Media Support
  media: { type: [KnowledgeMediaSchema], default: [] },
  featuredImage: { type: String },
  // Document & Attachment Management
  attachments: { type: [KpDocumentAttachmentSchema], default: [] },
  // Module Linking & Relationships
  linkedProductIds: { type: [String], default: [] },
  linkedServiceIds: { type: [String], default: [] },
  linkedProjectIds: { type: [String], default: [] },
  linkedTeamIds: { type: [String], default: [] },
  linkedDocumentIds: { type: [String], default: [] },
  linkedCampaignIds: { type: [String], default: [] },
  linkedWikiArticleId: { type: String, default: '' },
  relatedKnowledgePanelIds: { type: [String], default: [] },
  // AI-Generated Content History
  aiGeneratedContent: { type: [AIGeneratedContentSchema], default: [] },
  // Import/Export Metadata
  importedFrom: { type: String },
  importedAt: { type: String },
  lastExportedAt: { type: String },
  lastExportedFormat: { type: String },
}, {
  timestamps: true
});

// ============================================
// INDEXES
// ============================================

KnowledgePanelSchema.index({ companyId: 1 });
KnowledgePanelSchema.index({ companyId: 1, panelStatus: 1 });
KnowledgePanelSchema.index({ companyId: 1, status: 1 });
KnowledgePanelSchema.index({ companyId: 1, category: 1 });
KnowledgePanelSchema.index({ companyId: 1, isFeatured: 1 });

// ============================================
// EXPORT
// ============================================

export const KnowledgePanel = mongoose.model<IKnowledgePanel>('KnowledgePanel', KnowledgePanelSchema);