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

export interface ICMS extends Document {
  title: string;
  slug: string;
  content: string;
  featured_image?: string; // Path to stored image file
  meta_title?: string;
  meta_keywords?: string[];
  status: boolean;
  createdAt: Date;
  updatedAt: Date;
}

const CMSSchema: Schema = new Schema(
  {
    title: {
      type: String,
      required: [true, 'Title is required'],
      trim: true,
      maxlength: [200, 'Title cannot exceed 200 characters']
    },

    slug: {
      type: String,
      required: true,
      unique: true,
      trim: true,
      lowercase: true
    },

    content: {
      type: String,
      required: [true, 'Content is required'],
      trim: true
    },

    featured_image: {
      type: String,
      trim: true
    },

    meta_title: {
      type: String,
      trim: true,
      maxlength: [60, 'Meta title cannot exceed 60 characters']
    },

    meta_keywords: [{
      type: String,
      trim: true,
      maxlength: [50, 'Each keyword cannot exceed 50 characters']
    }],

    status: {
      type: Boolean,
      default: true
    }
  },
  {
    timestamps: true
  }
);

// ✅ Indexes
CMSSchema.index({ status: 1 });
CMSSchema.index({ slug: 1 });

// ✅ Pre-save middleware to generate slug
CMSSchema.pre('save', function(this: ICMS) {
  if (this.isModified('title') && !this.slug) {
    this.slug = this.title
      .toLowerCase()
      .trim()
      .replace(/[^\w\s-]/g, '')
      .replace(/\s+/g, '-')
      .replace(/--+/g, '-');
  }
});

export default mongoose.models.CMS || mongoose.model<ICMS>('CMS', CMSSchema);