import mongoose, { Document, Schema } from 'mongoose';
import slugify from 'slugify';

export interface ILocalizedString {
  en: string;
  zh: string;
}

const localizedStringSchema = {
  en: { type: String, default: '' },
  zh: { type: String, default: '' },
};

const localizedStringRequired = {
  en: { type: String, required: true },
  zh: { type: String, default: '' },
};

export interface IPost extends Document {
  title: ILocalizedString;
  slug: string;
  content: ILocalizedString;
  excerpt?: ILocalizedString;
  featuredImage?: string;
  videoUrl?: string;
  videoThumbnail?: string;
  category: string;
  tags: string[];
  status: 'draft' | 'published' | 'archived';
  author: mongoose.Types.ObjectId;
  readTime?: number;
  views: number;
  seo: {
    title?: string;
    description?: string;
    keywords?: string[];
    ogImage?: string;
  };
  publishedAt?: Date;
  createdAt: Date;
  updatedAt: Date;
}

const postSchema = new Schema<IPost>(
  {
    title: {
      type: localizedStringRequired,
      required: true,
    },
    slug: {
      type: String,
      unique: true,
      lowercase: true,
    },
    content: {
      type: localizedStringRequired,
      required: true,
    },
    excerpt: {
      type: localizedStringSchema,
    },
    featuredImage: String,
    videoUrl: String,
    videoThumbnail: String,
    category: {
      type: String,
      required: true,
      default: 'General',
    },
    tags: [{
      type: String,
      lowercase: true,
      trim: true,
    }],
    status: {
      type: String,
      enum: ['draft', 'published', 'archived'],
      default: 'draft',
    },
    author: {
      type: Schema.Types.ObjectId,
      ref: 'User',
      required: true,
    },
    readTime: Number,
    views: {
      type: Number,
      default: 0,
    },
    seo: {
      title: String,
      description: String,
      keywords: [String],
      ogImage: String,
    },
    publishedAt: Date,
  },
  {
    timestamps: true,
  }
);

postSchema.pre('save', function () {
  if (this.isModified('title') && !this.slug) {
    const enTitle = typeof this.title === 'object' ? this.title.en : (this.title as string);
    this.slug = slugify(enTitle || '', { lower: true, strict: true });
  }

  if (this.isModified('content')) {
    const enContent = typeof this.content === 'object' ? this.content.en : (this.content as string);
    if (enContent) {
      const wordCount = enContent.split(/\s+/).length;
      this.readTime = Math.ceil(wordCount / 200);
    }
  }

  if (this.isModified('content') && (!this.excerpt || (!this.excerpt.en && !this.excerpt.zh))) {
    const content = typeof this.content === 'object' ? this.content : { en: this.content as string, zh: '' };
    const enPlain = (content.en || '').replace(/<[^>]*>/g, '');
    const zhPlain = (content.zh || '').replace(/<[^>]*>/g, '');
    this.excerpt = {
      en: enPlain.substring(0, 250) + (enPlain.length > 250 ? '...' : ''),
      zh: zhPlain.substring(0, 250) + (zhPlain.length > 250 ? '...' : ''),
    } as any;
  }

  if (this.status === 'published' && !this.publishedAt) {
    this.publishedAt = new Date();
  }
});

postSchema.index({ status: 1, publishedAt: -1 });
postSchema.index({ category: 1 });
postSchema.index({ tags: 1 });

export const Post = mongoose.model<IPost>('Post', postSchema);
