const mongoose = require("mongoose");
const slugify = require("slugify");

const blogSchema = new mongoose.Schema(
  {
    title: {
      type: String,
      required: [true, "A blog must have a title"],
      unique: true,
      trim: true,
    },
    slug: String,
    content: {
      type: String,
      required: [true, "A blog must have content"],
    },
    coverImage: {
      type: String,
      required: [true, "A blog must have a cover image"],
    },
    // Optional: Short summary for cards
    summary: {
      type: String,
      trim: true,
      maxLength: 300,
    },
    author: {
      type: mongoose.Schema.ObjectId,
      ref: "User", // Assuming you have a User model
      required: [true, "A blog must have an author"],
    },
    category: {
      type: String,
      default: "General",
      trim: true,
    },
    tags: [String],
    isPublished: {
      type: Boolean,
      default: true,
    },
    views: {
      type: Number,
      default: 0,
    },
  },
  {
    timestamps: true,
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  }
);

// Middleware to create slug from title
blogSchema.pre("save", function (next) {
  if (this.isModified("title")) {
    this.slug = slugify(this.title, { lower: true });
  }
  next();
});

// Middleware to populate author details on find
blogSchema.pre(/^find/, function (next) {
  this.populate({
    path: "author",
    select: "name photo role", // Only select necessary fields
  });
  next();
});

const Blog = mongoose.model("Blog", blogSchema);
module.exports = Blog;
