const mongoose = require("mongoose");

const therapistProfileSchema = new mongoose.Schema({
  // Link to user account
  user: { 
    type: mongoose.Schema.Types.ObjectId, 
    ref: "User", 
    required: true,
    unique: true,
    index: true
  },
  
  // Basic Information
  fullName: { 
    type: String, 
    required: true 
  },
  professionalTitle: { 
    type: String, 
    required: true,
    enum: [
      "Clinical Psychologist",
      "Therapist", 
      "Licensed Clinical Social Worker",
      "Marriage and Family Therapist",
      "Licensed Professional Counselor",
      "Psychiatrist",
      "Psychoanalyst",
      "Art Therapist",
      "Music Therapist",
      "Other"
    ]
  },
  yearsOfExperience: { 
    type: Number, 
    required: true,
    min: 0,
    max: 50 
  },
  certifications: [{
    name: { type: String },
    issuingBody: { type: String },
    issueDate: { type: Date },
    expiryDate: { type: Date },
    certificateUrl: { type: String } // For uploaded certificates
  }],
  
  // Therapy Delivery Preferences
  therapyModes: [{
    type: String,
    enum: ["Online", "Offline", "Hybrid"],
    required: true
  }],
  therapyTypes: [{
    type: String,
    enum: [
      "Individual Therapy",
      "Couples Therapy", 
      "Family Therapy",
      "Therapy for Children"
    ],
    required: true
  }],
  
  // Availability Management
  weeklyAvailability: {
    monday: {
      available: { type: Boolean, default: false },
      slots: [{
        startTime: { type: String, match: /^([01]\d|2[0-3]):([0-5]\d)$/ },
        endTime: { type: String, match: /^([01]\d|2[0-3]):([0-5]\d)$/ }
      }]
    },
    tuesday: {
      available: { type: Boolean, default: false },
      slots: [{
        startTime: { type: String, match: /^([01]\d|2[0-3]):([0-5]\d)$/ },
        endTime: { type: String, match: /^([01]\d|2[0-3]):([0-5]\d)$/ }
      }]
    },
    wednesday: {
      available: { type: Boolean, default: false },
      slots: [{
        startTime: { type: String, match: /^([01]\d|2[0-3]):([0-5]\d)$/ },
        endTime: { type: String, match: /^([01]\d|2[0-3]):([0-5]\d)$/ }
      }]
    },
    thursday: {
      available: { type: Boolean, default: false },
      slots: [{
        startTime: { type: String, match: /^([01]\d|2[0-3]):([0-5]\d)$/ },
        endTime: { type: String, match: /^([01]\d|2[0-3]):([0-5]\d)$/ }
      }]
    },
    friday: {
      available: { type: Boolean, default: false },
      slots: [{
        startTime: { type: String, match: /^([01]\d|2[0-3]):([0-5]\d)$/ },
        endTime: { type: String, match: /^([01]\d|2[0-3]):([0-5]\d)$/ }
      }]
    },
    saturday: {
      available: { type: Boolean, default: false },
      slots: [{
        startTime: { type: String, match: /^([01]\d|2[0-3]):([0-5]\d)$/ },
        endTime: { type: String, match: /^([01]\d|2[0-3]):([0-5]\d)$/ }
      }]
    },
    sunday: {
      available: { type: Boolean, default: false },
      slots: [{
        startTime: { type: String, match: /^([01]\d|2[0-3]):([0-5]\d)$/ },
        endTime: { type: String, match: /^([01]\d|2[0-3]):([0-5]\d)$/ }
      }]
    }
  },
  
  maxSessionsPerDay: { 
    type: Number, 
    default: 7,
    min: 1,
    max: 12 
  },
  breakDurationMinutes: { 
    type: Number, 
    default: 30,
    min: 15,
    max: 120 
  },
  
  // Unavailable dates (for holidays, vacations, etc.)
  unavailableDates: [{
    date: { type: Date, required: true },
    reason: { type: String },
    isRecurring: { type: Boolean, default: false } // For recurring holidays
  }],
  
  // Notification Preferences
  notificationPreferences: {
    emailAlerts: { type: Boolean, default: true },
    smsNotifications: { type: Boolean, default: true },
    dashboardReminders: { type: Boolean, default: true },
    appointmentReminders: { type: Boolean, default: true },
    planUpdates: { type: Boolean, default: true },
    feedbackNotifications: { type: Boolean, default: true }
  },
  
  // Account Settings
  isActive: { type: Boolean, default: true },
  displayLanguage: { 
    type: String, 
    enum: ["English", "Hindi", "Both"],
    default: "English" 
  },
  
  // Admin Approval Status
  approvalStatus: {
    type: String,
    enum: ["pending", "approved", "rejected", "changes_requested"],
    default: "approved"
  },
  approvalHistory: [{
    status: { 
      type: String,
      enum: ["pending", "approved", "rejected", "changes_requested"]
    },
    adminId: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
    reason: { type: String },
    changedAt: { type: Date, default: Date.now },
    changes: { type: mongoose.Schema.Types.Mixed } // Store what was changed
  }],
  
  // Profile completion tracking
  profileCompletionPercentage: { 
    type: Number, 
    default: 0,
    min: 0,
    max: 100 
  },
  
  // Specializations and additional info
  specializations: [{ type: String }],
  languages: [{ 
    type: String,
    enum: ["English", "Hindi", "Bengali", "Tamil", "Telugu", "Marathi", "Gujarati", "Kannada", "Malayalam", "Punjabi", "Urdu", "Other"]
  }],
  bio: { type: String, maxlength: 1000 },
  
  // Timezone for scheduling
  timezone: { 
    type: String, 
    default: "Asia/Kolkata" 
  },
  
}, { timestamps: true });

// Indexes for better performance
therapistProfileSchema.index({ approvalStatus: 1 });
therapistProfileSchema.index({ isActive: 1 });
therapistProfileSchema.index({ "therapyModes": 1 });
therapistProfileSchema.index({ "therapyTypes": 1 });

// Pre-save middleware to calculate profile completion percentage
therapistProfileSchema.pre('save', function(next) {
  const requiredFields = [
    'fullName', 'professionalTitle', 'yearsOfExperience', 
    'therapyModes', 'therapyTypes'
  ];
  
  const optionalFields = [
    'certifications', 'specializations', 'languages', 'bio'
  ];
  
  let completedRequired = 0;
  let completedOptional = 0;
  
  // Check required fields
  requiredFields.forEach(field => {
    if (this[field] && (Array.isArray(this[field]) ? this[field].length > 0 : true)) {
      completedRequired++;
    }
  });
  
  // Check optional fields
  optionalFields.forEach(field => {
    if (this[field] && (Array.isArray(this[field]) ? this[field].length > 0 : this[field].toString().trim().length > 0)) {
      completedOptional++;
    }
  });
  
  // Check availability setup
  const hasAvailability = Object.values(this.weeklyAvailability).some(day => day.available && day.slots.length > 0);
  if (hasAvailability) completedOptional++;
  
  // Calculate percentage (required fields are 70%, optional are 30%)
  const requiredPercentage = (completedRequired / requiredFields.length) * 70;
  const optionalPercentage = (completedOptional / (optionalFields.length + 1)) * 30;
  
  this.profileCompletionPercentage = Math.round(requiredPercentage + optionalPercentage);
  
  next();
});

// Method to check if therapist is available on a specific date and time
therapistProfileSchema.methods.isAvailableAt = function(date, startTime, endTime) {
  const dayOfWeek = date.toLocaleDateString('en-US', { weekday: 'lowercase' });
  const dayAvailability = this.weeklyAvailability[dayOfWeek];
  
  if (!dayAvailability || !dayAvailability.available) {
    return false;
  }
  
  // Check if the requested time falls within any available slot
  return dayAvailability.slots.some(slot => {
    return startTime >= slot.startTime && endTime <= slot.endTime;
  });
};

// Method to get available slots for a specific date
therapistProfileSchema.methods.getAvailableSlotsForDate = function(date) {
  const dayOfWeek = date.toLocaleDateString('en-US', { weekday: 'lowercase' });
  const dayAvailability = this.weeklyAvailability[dayOfWeek];
  
  if (!dayAvailability || !dayAvailability.available) {
    return [];
  }
  
  return dayAvailability.slots;
};

module.exports = mongoose.model("TherapistProfile", therapistProfileSchema);
