const mongoose = require("mongoose");

const { slugify } = require("../Utils/slug");

const postSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: [true, "Your article must have a name"],
      trim: true,
      minlength: [10, "The article name must be at least 10 characters"],
    },

    title: {
      type: String,
      required: [true, "Your article must have a title"],
    },
    introduction: { type: String },
    slug: {
      type: String,
      unique: [true, "This slug has already been used"],
      required: [true, "Your article needs a slug"],
      minlength: [10, "The slug must be at least 10 characters long"],
    },

    description: {
      type: String,
      required: [true, "Your article must include meta description"],
      maxlength: [155, "Meta description can be a maximum of 155 characters"],
      minlength: [50, "Meta description must be at least 50 characters"],
    },

    imageCover: {
      type: String,
      required: [true, "The article must include a cover image"],
    },

    category: {
      type: String,
      required: [true, "Your post must have a category."],
    },

    mainText: {
      type: String,
      required: [true, "The article is missing main content"],
    },

    tags: {
      type: String,
      defualt: "",
    },

    publishedAt: {
      type: Date,
      default: Date.now(),
    },

    createdAt: {
      type: Date,
      default: Date.now(),
    },

    author: {
      type: mongoose.ObjectId,
      ref: "User",
      required: [true, "Your article needs an author's name"],
    },

    status: {
      type: String,
      defualt: [],
      enum: ["private", "public"],
    },
    relatedPosts: [{ type: mongoose.ObjectId, ref: "Post" }],
    promote: {
      type: Boolean,
      defualt: false,
    },

    HeaderHTML: String,
    FooterHTML: String,
  },
  {
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  }
);

postSchema.pre("save", function (next) {
  this.slug = slugify(this.slug);
  next();
});

postSchema.pre("save", function (next) {
  this.createdAt = Date.now();
  next();
});

const Post = mongoose.model("Post", postSchema);

module.exports = Post;
