const mongoose = require("mongoose");
const slugify = require("slugify");
const validator = require("validator");
const options = { discriminatorKey: "kind", collection: "staff" };

const staffSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: [true, "Staff member must have a name"],
      trim: true,
      unique: true,
    },
    slug: String,
    email: {
      type: String,
      required: [true, "A user must have an email"],
      unique: true,
      lowercase: true,
      trim: true,
      validate: [validator.isEmail, "Please provide a valid email"],
    },
    title: {
      type: String,
      enum: ["Dr.", "Mr.", "Mrs.", "Ms.", "Eng.", "Prof."],
      default: "Mr.",
      required: [true, "Title is required"],
    },
    subtitle: { type: String, trim: true },
    description: { type: String, trim: true },
    age: Number,
    gender: {
      type: String,
      enum: ["male", "female"],
      required: [true, "Gender is required"],
    },
    salary: {
      type: Number,
      select: false,
    },
    currency: {
      type: String,
      default: "SAR",
      enum: ["SAR", "USD", "EGP", "EUR"],
    },
    photo: {
      type: String,
      // Default will be set by pre-save hook
    },
    role: {
      type: mongoose.Schema.ObjectId,
      ref: "StaffRole",
      required: [true, "Staff must have a role"],
    },
    socialMedia: {
      facebook: { type: String, trim: true },
      twitter: { type: String, trim: true },
      linkedin: { type: String, trim: true },
      github: { type: String, trim: true },
      website: { type: String, trim: true },
    },
  },
  {
    timestamps: true,
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
    ...options,
  }
);

// --- Middleware ---

// 1. Set Slug & Default Photo
staffSchema.pre("save", function (next) {
  // Slugify Name
  if (this.name) {
    this.slug = slugify(this.name, { lower: true });
  }

  // Set Default Photo if none provided
  if (!this.photo) {
    if (this.gender === "female") {
      this.photo = "defaultFemale.png";
    } else {
      this.photo = "defaultMale.png";
    }
  }
  next();
});

// 2. Populate Role automatically
staffSchema.pre(/^find/, function (next) {
  this.populate({
    path: "role",
    select: "name",
  });
  next();
});

const Staff = mongoose.model("Staff", staffSchema);
module.exports = Staff;
