const mongoose = require("mongoose");
const Staff = require("./staffModel");

const instructorSchema = new mongoose.Schema(
  {
    // ✅ Add Rating Fields Here (Only for Instructors)
    ratingsAverage: {
      type: Number,
      default: 4.5,
      min: [1, "Rating must be above 1.0"],
      max: [5, "Rating must be below 5.0"],
      // Round to 1 decimal place (e.g., 4.6666 -> 4.7)
      set: (val) => Math.round(val * 10) / 10,
    },
    ratingsQuantity: {
      type: Number,
      default: 0,
    },
  },
  {
    // ✅ REQUIRED: Allow virtuals to be included in JSON output
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  }
);

// ✅ DEFINE VIRTUAL: Inverse Relationship to Courses
instructorSchema.virtual("courses", {
  ref: "Course", // The Model to search
  foreignField: "instructors._id", // The field in Course model that has the ID (embedded object)
  localField: "_id", // The field in Instructor model (my ID)
});

// ✅ MIDDLEWARE: Populate courses automatically when finding an Instructor
instructorSchema.pre(/^find/, function (next) {
  this.populate({
    path: "courses",
    select: "name coverImage price mode status",
  });
  next();
});

const Instructor = Staff.discriminator("Instructor", instructorSchema);

module.exports = Instructor;
