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

// Blog Interface
export interface IBlog extends Document {
  title: string;
  sub_title: string;
  images: string[]; // Array of image URLs
  description: string;
  short_description: string;
  createdAt: Date;
  updatedAt: Date;
}

const BlogSchema = new Schema(
  {
    title: {
      type: String,
      required: true,
      trim: true,
    },
    sub_title: {
      type: String,
      required: true,
      trim: true,
    },
    slug: {
      type: String,
      required: true,
      trim: true,
    },
    images: {
      type: [String], // Array of strings for image URLs
      default: [],
      validate: {
        validator: function (images: string[]) {
          return images.every(
            (image) => typeof image === "string" && image.length > 0,
          );
        },
        message: "All images must be valid URLs or paths",
      },
    },
    description: {
      type: String,
      required: true,
    },
    short_description: {
      type: String,
      required: true,
      maxlength: 500, // Optional: limit short description length
    },
  },
  { timestamps: true },
);

// Optional: Add index for better search performance
BlogSchema.index({ title: "text", short_description: "text" });

// Optional: Pre-save middleware to trim strings
BlogSchema.pre("save", async function () {
  if (this.title) this.title = this.title.trim();
  if (this.sub_title) this.sub_title = this.sub_title.trim();
  if (this.short_description) {
    this.short_description = this.short_description.trim();
  }
  if (this.description) {
    this.description = this.description.trim();
  }
});

export default mongoose.models.Blog ||
  mongoose.model<IBlog>("Blog", BlogSchema);
