const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');

const scheduleSchema = new mongoose.Schema({
  day: {
    type: String,
    required: [true, 'Day is required'],
    enum: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
  },
  time: {
    type: String,
    required: [true, 'Time slot is required'],
    match: [/^([0-1]?[0-9]|2[0-3]):[0-5][0-9] - ([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/, 'Please enter time in format "HH:MM - HH:MM"']
  },
  class: {
    type: String,
    required: [true, 'Class is required'],
    trim: true
  },
  subject: {
    type: String,
    required: [true, 'Subject is required'],
    trim: true
  },
  room: {
    type: String,
    required: [true, 'Room is required'],
    trim: true
  },
  isActive: {
    type: Boolean,
    default: true
  }
});

const teacherSchema = new mongoose.Schema({
  // Personal Information
  firstName: {
    type: String,
    required: [true, 'First name is required'],
    trim: true
  },
  lastName: {
    type: String,
    required: [true, 'Last name is required'],
    trim: true
  },
  gender: {
    type: String,
    required: [true, 'Gender is required'],
    enum: ['Male', 'Female', 'Other']
  },
  dob: {
    type: Date,
    required: [true, 'Date of birth is required']
  },
  email: {
    type: String,
    required: [true, 'Email is required'],
    unique: true,
    trim: true,
    lowercase: true,
    match: [/^[^\s@]+@[^\s@]+\.[^\s@]+$/, 'Please enter a valid email']
  },
  phone: {
    type: String,
    required: [true, 'Phone number is required'],
    match: [/^\+?\d{10,15}$/, 'Please enter a valid phone number']
  },
  address: {
    type: String,
    trim: true
  },
  qualification: {
    type: String,
    required: [true, 'Qualification is required'],
    enum: ['Bachelor\'s Degree', 'Master\'s Degree', 'PhD', 'Teaching Certificate', 'Other']
  },
  
  // Professional Information
  department: {
    type: String,
    required: [true, 'Department is required'],
    enum: ['Mathematics', 'Science', 'English', 'Social Studies', 'Arts', 'Physical Education', 'Computer Science', 'Foreign Languages']
  },
  subject: {
    type: String,
    required: [true, 'Subject is required'],
    trim: true
  },
  joiningDate: {
    type: Date,
    required: [true, 'Joining date is required']
  },
  salary: {
    type: Number,
    min: 0
  },
  experience: {
    type: String,
    required: [true, 'Experience is required'],
    enum: ['0-1 years', '1-3 years', '3-5 years', '5-10 years', '10+ years']
  },
  teacherId: {
    type: String,
    required: [true, 'Teacher ID is required'],
    unique: true,
    trim: true
  },
  
  // Schedule Information
  schedule: [scheduleSchema],
  
  // Working Days and Hours
  workingDays: {
    type: [String],
    enum: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
    default: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
  },
  workingHours: {
    start: {
      type: String,
      default: '08:00',
      match: [/^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/, 'Please enter time in format "HH:MM"']
    },
    end: {
      type: String,
      default: '16:00',
      match: [/^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/, 'Please enter time in format "HH:MM"']
    }
  },
  
  // Account Information
  password: {
    type: String,
    required: [true, 'Password is required'],
    minlength: [6, 'Password must be at least 6 characters long']
  },
  
  // Emergency Contact
  emergencyContact: {
    type: String,
    trim: true
  },
  emergencyPhone: {
    type: String,
    trim: true
  },
  
  // Photo
  photo: {
    type: String,
    default: 'https://images.pexels.com/photos/5212334/pexels-photo-5212334.jpeg'
  },
  
  // Status
  isActive: {
    type: Boolean,
    default: true
  }
}, {
  timestamps: true
});

// Hash password before saving
teacherSchema.pre('save', async function(next) {
  if (!this.isModified('password')) return next();
  
  try {
    const salt = await bcrypt.genSalt(10);
    this.password = await bcrypt.hash(this.password, salt);
    next();
  } catch (error) {
    next(error);
  }
});

// Method to compare password
teacherSchema.methods.comparePassword = async function(candidatePassword) {
  return await bcrypt.compare(candidatePassword, this.password);
};

// Virtual for full name
teacherSchema.virtual('fullName').get(function() {
  return `${this.firstName} ${this.lastName}`;
});

// Virtual for total classes per week
teacherSchema.virtual('totalClasses').get(function() {
  return this.schedule.filter(item => item.isActive).length;
});

// Virtual for working days count
teacherSchema.virtual('workingDaysCount').get(function() {
  const activeScheduleDays = [...new Set(this.schedule.filter(item => item.isActive).map(item => item.day))];
  return activeScheduleDays.length;
});

// Index for better query performance
teacherSchema.index({ teacherId: 1 });
teacherSchema.index({ email: 1 });
teacherSchema.index({ 'schedule.day': 1, 'schedule.time': 1 });

module.exports = mongoose.model('Teacher', teacherSchema);