/**
 * Wikipedia Article Model
 * Manages Wikipedia article drafts, notability assessments, citations, and monitoring for the PR Content Studio
 */

import mongoose, { Schema, Document } from 'mongoose';

// ============================================
// TYPE DEFINITIONS
// ============================================

/**
 * Editorial lifecycle PLUS the two PR Content dashboard statuses it did not
 * already cover ('generated', 'reviewed') — Wikipedia articles are listed on
 * that dashboard and can be marked with them. 'draft' and 'published' were
 * already shared. Additive; existing values unchanged.
 */
export type WikipediaArticleStatus = 'draft' | 'in-progress' | 'submitted' | 'published' | 'rejected' | 'needs-editing'
  | 'generated' | 'reviewed';

export type CitationType = 'primary' | 'secondary' | 'tertiary';
export type CitationReliability = 'high' | 'medium' | 'low';
export type CitationIndependence = 'independent' | 'affiliated' | 'self-published';
export type CitationStatus = 'verified' | 'pending' | 'failed';

export type EditType = 'minor' | 'major' | 'vandalism' | 'revert';

export interface INotabilityCriterion {
  criterion: string;
  met: boolean;
  evidence: string;
}

export interface IArticleSection {
  sectionTitle: string;
  content: string;
  citations: string[];
  status: string;
}

export interface ICitation {
  url: string;
  title: string;
  type: CitationType;
  reliability: CitationReliability;
  independence: CitationIndependence;
  excerpt: string;
  archivedUrl?: string;
  archivedDate?: string;
  status: CitationStatus;
}

export interface IDocumentAttachment {
  url: string;
  name: string;
  type: string;
  size?: number;
}

export interface ISubmissionEntry {
  date: string;
  status: string;
  reviewerFeedback: string;
  revisionNotes: string;
  documents: IDocumentAttachment[];
}

export interface IMonitorAlert {
  date: string;
  editType: EditType;
  summary: string;
  diffUrl: string;
  resolved: boolean;
}

export interface IInfobox {
  name: string;
  type: string;
  industry: string;
  founded: string;
  headquarters: string;
  website: string;
}

export interface IWikipediaArticle extends Document {
  companyId: string;
  title: string;
  summary: string;
  notabilityAssessment: string;
  infobox: IInfobox;
  status: WikipediaArticleStatus;
  notabilityScore: number;
  notabilityCriteria: INotabilityCriterion[];
  sections: IArticleSection[];
  citations: ICitation[];
  coiDisclosure: string;
  submissionHistory: ISubmissionEntry[];
  monitorAlerts: IMonitorAlert[];
  lastMonitoredDate: string;
  tags: string[];
  version: number;
  language?: string;
  createdAt: Date;
  updatedAt: Date;
}

// ============================================
// SUB-SCHEMAS
// ============================================

const NotabilityCriterionSchema = new Schema<INotabilityCriterion>({
  criterion: { type: String, default: '' },
  met: { type: Boolean, default: false },
  evidence: { type: String, default: '' }
}, { _id: false });

const ArticleSectionSchema = new Schema<IArticleSection>({
  sectionTitle: { type: String, default: '' },
  content: { type: String, default: '' },
  citations: [{ type: String }],
  status: { type: String, default: 'draft' }
}, { _id: false });

const CitationSchema = new Schema<ICitation>({
  url: { type: String, default: '' },
  title: { type: String, default: '' },
  type: {
    type: String,
    enum: ['primary', 'secondary', 'tertiary'],
    default: 'secondary'
  },
  reliability: {
    type: String,
    enum: ['high', 'medium', 'low'],
    default: 'medium'
  },
  independence: {
    type: String,
    enum: ['independent', 'affiliated', 'self-published'],
    default: 'independent'
  },
  excerpt: { type: String, default: '' },
  archivedUrl: { type: String, default: '' },
  archivedDate: { type: String, default: '' },
  status: {
    type: String,
    enum: ['verified', 'pending', 'failed'],
    default: 'pending'
  }
}, { _id: false });

const DocumentAttachmentSchema = new Schema<IDocumentAttachment>({
  url: { type: String, default: '' },
  name: { type: String, default: '' },
  type: { type: String, default: '' },
  size: { type: Number, default: 0 },
}, { _id: false });

const SubmissionEntrySchema = new Schema<ISubmissionEntry>({
  date: { type: String, default: '' },
  status: { type: String, default: '' },
  reviewerFeedback: { type: String, default: '' },
  revisionNotes: { type: String, default: '' },
  documents: { type: [DocumentAttachmentSchema], default: [] }
}, { _id: false });

const MonitorAlertSchema = new Schema<IMonitorAlert>({
  date: { type: String, default: '' },
  editType: {
    type: String,
    enum: ['minor', 'major', 'vandalism', 'revert'],
    default: 'minor'
  },
  summary: { type: String, default: '' },
  diffUrl: { type: String, default: '' },
  resolved: { type: Boolean, default: false }
}, { _id: false });

const InfoboxSchema = new Schema<IInfobox>({
  name: { type: String, default: '' },
  type: { type: String, default: '' },
  industry: { type: String, default: '' },
  founded: { type: String, default: '' },
  headquarters: { type: String, default: '' },
  website: { type: String, default: '' }
}, { _id: false });

// ============================================
// MAIN SCHEMA
// ============================================

const WikipediaArticleSchema = new Schema<IWikipediaArticle>({
  companyId: {
    type: String,
    required: [true, 'Company ID is required'],
    index: true
  },
  title: {
    type: String,
    required: [true, 'Title is required'],
    trim: true,
    maxlength: [500, 'Title cannot exceed 500 characters']
  },
  summary: {
    type: String,
    default: '',
    trim: true
  },
  notabilityAssessment: {
    type: String,
    default: '',
    trim: true
  },
  infobox: { type: InfoboxSchema, default: () => ({}) },
  status: {
    type: String,
    enum: ['draft', 'in-progress', 'submitted', 'published', 'rejected', 'needs-editing',
           'generated', 'reviewed'],
    default: 'draft'
  },
  notabilityScore: { type: Number, default: 0 },
  notabilityCriteria: { type: [NotabilityCriterionSchema], default: [] },
  sections: { type: [ArticleSectionSchema], default: [] },
  citations: { type: [CitationSchema], default: [] },
  coiDisclosure: { type: String, default: '' },
  submissionHistory: { type: [SubmissionEntrySchema], default: [] },
  monitorAlerts: { type: [MonitorAlertSchema], default: [] },
  lastMonitoredDate: { type: String, default: '' },
  tags: [{ type: String, trim: true }],
  version: { type: Number, default: 1 },
  language: { type: String, default: 'en' },
}, {
  timestamps: true
});

// ============================================
// INDEXES
// ============================================

WikipediaArticleSchema.index({ companyId: 1, status: 1 });
WikipediaArticleSchema.index({ companyId: 1, updatedAt: -1 });

// ============================================
// EXPORT
// ============================================

export const WikipediaArticle = mongoose.model<IWikipediaArticle>('WikipediaArticle', WikipediaArticleSchema);